-
Notifications
You must be signed in to change notification settings - Fork 0
/
tripper.go
35 lines (29 loc) · 920 Bytes
/
tripper.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package httpauth
import (
"fmt"
"net/http"
"github.com/Bplotka/go-tokenauth"
"github.com/pkg/errors"
)
type Tripper struct {
parent http.RoundTripper
auth tokenauth.Source
headerName string
}
// NewTripper constructs Tripper that is able to inject any token as Bearer inside given Header name.
func NewTripper(parent http.RoundTripper, auth tokenauth.Source, headerName string) http.RoundTripper {
return &Tripper{
parent: parent,
auth: auth,
headerName: headerName,
}
}
// RoundTrip wraps parent RoundTrip and injects retrieved Token into specified Header.
func (t *Tripper) RoundTrip(req *http.Request) (*http.Response, error) {
token, err := t.auth.Token(req.Context())
if err != nil {
return nil, errors.Wrap(err, "httpauth.Tripper: failed to retrieve valid Auth Token")
}
req.Header.Set(t.headerName, fmt.Sprintf("Bearer %s", token))
return t.parent.RoundTrip(req)
}