AddAuthTokenHeader adds an authentication token header for the host specified by the request.
(rt http.RoundTripper, cfg tokenGetter)
| 150 | |
| 151 | // AddAuthTokenHeader adds an authentication token header for the host specified by the request. |
| 152 | func AddAuthTokenHeader(rt http.RoundTripper, cfg tokenGetter) http.RoundTripper { |
| 153 | return &funcTripper{roundTrip: func(req *http.Request) (*http.Response, error) { |
| 154 | // If the header is already set in the request, don't overwrite it. |
| 155 | if req.Header.Get(authorization) == "" { |
| 156 | var redirectHostnameChange bool |
| 157 | if req.Response != nil && req.Response.Request != nil { |
| 158 | redirectHostnameChange = getHost(req) != getHost(req.Response.Request) |
| 159 | } |
| 160 | // Only set header if an initial request or redirect request to the same host as the initial request. |
| 161 | // If the host has changed during a redirect do not add the authentication token header. |
| 162 | if !redirectHostnameChange { |
| 163 | hostname := ghauth.NormalizeHostname(getHost(req)) |
| 164 | if token, _ := cfg.ActiveToken(hostname); token != "" { |
| 165 | req.Header.Set(authorization, fmt.Sprintf("token %s", token)) |
| 166 | } |
| 167 | } |
| 168 | } |
| 169 | return rt.RoundTrip(req) |
| 170 | }} |
| 171 | } |
| 172 | |
| 173 | // ExtractHeader extracts a named header from any response received by this client and, |
| 174 | // if non-blank, saves it to dest. |
no test coverage detected