master
go 29 lines 885 Bytes
Raw
1 package auth
2
3 import "net/http"
4
5 var _ http.RoundTripper = &AuthorizedRoundTripper{}
6
7 type AuthorizedRoundTripper struct {
8 authorization string
9 roundTripper http.RoundTripper
10 }
11
12 // NewAuthorizedRoundTripper creates a new [http.RoundTripper] that will set the
13 // Authorization HTTP header with the value of [authorization]. The given [roundTripper] is
14 // the base [http.RoundTripper]. If it is nil, [http.DefaultTransport] is used.
15 func NewAuthorizedRoundTripper(authorization string, roundTripper http.RoundTripper) http.RoundTripper {
16 if roundTripper == nil {
17 roundTripper = http.DefaultTransport
18 }
19
20 return &AuthorizedRoundTripper{
21 authorization: authorization,
22 roundTripper: roundTripper,
23 }
24 }
25
26 func (tp *AuthorizedRoundTripper) RoundTrip(r *http.Request) (*http.Response, error) {
27 r.Header.Set("Authorization", tp.authorization)
28 return tp.roundTripper.RoundTrip(r)
29 }