-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.go
42 lines (35 loc) · 1.07 KB
/
client.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
36
37
38
39
40
41
42
package client
import (
"context"
"fmt"
"github.com/armory-io/go-commons/http/client/core"
"github.com/armory-io/go-commons/opentelemetry"
"net/http"
)
type (
bearerTokenRoundTripper struct {
base http.RoundTripper
tokenSupplier tokenSupplier
}
tokenSupplier interface {
GetToken(ctx context.Context) (string, error)
}
)
// NewAuthenticatedHTTPClient creates an http.Client that propagates OpenTelemetry trace headers and authenticates its requests
// with a bearer token header.
func NewAuthenticatedHTTPClient(supplier tokenSupplier, tracingConfig opentelemetry.Configuration) *http.Client {
c := core.NewHTTPClient(core.Parameters{Tracing: tracingConfig})
c.Transport = &bearerTokenRoundTripper{
tokenSupplier: supplier,
base: c.Transport,
}
return c
}
func (b *bearerTokenRoundTripper) RoundTrip(request *http.Request) (*http.Response, error) {
token, err := b.tokenSupplier.GetToken(request.Context())
if err != nil {
return nil, err
}
request.Header.Add("Authorization", fmt.Sprintf("Bearer %s", token))
return b.base.RoundTrip(request)
}