-
Notifications
You must be signed in to change notification settings - Fork 26
/
transport.go
45 lines (40 loc) · 1.07 KB
/
transport.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
43
44
45
package bot
import (
"fmt"
"io"
"net/http"
"strings"
)
type transport struct {
roundTripper http.RoundTripper
authenticator *Authenticator
}
// NewTransport returns a new transport based on the given inputs.
func NewTransport(
roundTripper http.RoundTripper,
uid,
sid,
privateKey string) (*transport, error) {
return &transport{
roundTripper: roundTripper,
authenticator: NewAuthenticator(uid, sid, privateKey),
}, nil
}
// RoundTrip implements the http.RoundTripper interface and wraps
// the base round tripper with logic to inject the API key auth-based HTTP headers
// into the request. Reference: https://pkg.go.dev/net/http#RoundTripper
func (t *transport) RoundTrip(req *http.Request) (*http.Response, error) {
body, err := io.ReadAll(req.Body)
if err != nil {
return nil, err
}
req.Body = io.NopCloser(strings.NewReader(string(body)))
jwt, err := t.authenticator.BuildJWT(
req.Method, req.URL.Path, string(body),
)
if err != nil {
return nil, err
}
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", jwt))
return t.roundTripper.RoundTrip(req)
}