Add Bearer Tokens With A Custom RoundTripper
Send every outgoing request through a custom RoundTripper that injects an Authorization Bearer header, cloning the request first so callers are never mutated.
Code
package main
import (
"fmt"
"io"
"net/http"
"net/http/httptest"
"os"
)
// tokenTransport 为每个出站请求注入令牌(token):认证细节收敛在一处
type tokenTransport struct {
token string
base http.RoundTripper
}
func (t *tokenTransport) RoundTrip(req *http.Request) (*http.Response, error) {
// RoundTripper 契约禁止修改调用方传入的请求:先克隆再改头
out := req.Clone(req.Context())
out.Header.Set("Authorization", "Bearer "+t.token)
transport := t.base
if transport == nil {
transport = http.DefaultTransport
}
return transport.RoundTrip(out)
}
func main() {
// httptest 起一个受保护后端,回显它看到的认证头
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "backend saw "+r.Header.Get("Authorization"))
}))
defer server.Close()
client := &http.Client{Transport: &tokenTransport{token: "secret-token-42"}}
resp, err := client.Get(server.URL)
if err != nil {
panic(err)
}
defer resp.Body.Close()
if _, err := io.Copy(os.Stdout, resp.Body); err != nil {
panic(err)
}
}Inside the snippet
Add Bearer Tokens With A Custom RoundTripper comes down to the functions RoundTrip and main.
Every fallible call checks err != nil (2 sites), so an error is handled where it happens rather than bubbling invisibly. A defer statement pins the cleanup to the function boundary rather than scattering it through the body.
Watch out for
- Error values are returned, not thrown — every call site must inspect
errbefore using the other return values.
Using it
The entry-point signature is func (t *tokenTransport) RoundTrip(req *http.Request) (*http.Response, error)
Key statements
if err != nil {
panic(err)
}
return transport.RoundTrip(out)
defer resp.Body.Close()
Interactive Tools for This Topic
Basic & Bearer Auth Header ToolEncode and decode HTTP Authorization Basic and Bearer headers locally with UTF-8 Base64 validation and automatic JWT claim and expiry inspection.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.JWT Expiry CalculatorDecode a JWT payload and convert its exp, iat, and nbf claims into UTC ISO timestamps, with an expired-or-valid verdict.Accept Header ParserParse an Accept header into media ranges with their quality values and specificity, sorted by preference for content negotiation debugging.
FAQ
- How are errors reported?
- As returned `error` values, checked at 2 sites — callers must branch on `err` before using the other return values. When a call fails in the entry flow, the run aborts via `panic(err)`.
- How do you run Add Bearer Tokens With A Custom RoundTripper?
- Run the file on its own; every call resolves against the standard surface it already imports.
Report a problem with this exampleOpens a pre-filled issue on GitHub.