You can decorate the client's Transport. For instance:
package main
import "net/http"
func main() {
client := http.DefaultClient
rt := WithHeader(client.Transport)
rt.Set("Authorization", "Bearer <token>")
client.Transport = rt
client.Get("http://example.com")
}
type withHeader struct {
http.Header
rt http.RoundTripper
}
func WithHeader(rt http.RoundTripper) withHeader {
if rt == nil {
rt = http.DefaultTransport
}
return withHeader{Header: make(http.Header), rt: rt}
}
func (h withHeader) RoundTrip(req *http.Request) (*http.Response, error) {
for k, v := range h.Header {
req.Header[k] = v
}
return h.rt.RoundTrip(req)
}
For the specific purpose of authorization tokens, you might be interested in the golang.org/x/oauth2 package, which does essentially the same, but also supports automatic token renewal:
package main
import (
"context"
"golang.org/x/oauth2"
)
func main() {
ctx := context.Background()
client := oauth2.NewClient(ctx, oauth2.StaticTokenSource(&oauth2.Token{
AccessToken: "<your token>",
TokenType: "Bearer",
}))
client.Get("http://example.com")
}