How to Use Bearer Token / OAuth2 in HTTP Requests in Go

Web
Send Bearer tokens in Go by setting the Authorization header to 'Bearer <token>' or configuring OAuthTokenProvider for database connections.

Add the Bearer token to the Authorization header using req.Header.Set("Authorization", "Bearer " + token) before executing the request. This approach works for standard net/http clients and matches the pattern used in Go's internal authentication logic.

package main

import (
	"fmt"
	"net/http"
)

func main() {
	token := "your-oauth-token"
	req, _ := http.NewRequest("GET", "https://api.example.com/data", nil)
	req.Header.Set("Authorization", "Bearer "+token)

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer resp.Body.Close()
	fmt.Println(resp.Status)
}

For PostgreSQL connections using pgx, configure the OAuthTokenProvider in the Config struct to return the token dynamically during the OAUTHBEARER SASL handshake.