-
Notifications
You must be signed in to change notification settings - Fork 0
/
transport.go
53 lines (40 loc) · 1.54 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
46
47
48
49
50
51
52
53
package n26api
import (
"fmt"
"net/http"
"github.com/nhatthm/n26api/pkg/auth"
"github.com/nhatthm/n26api/pkg/util"
)
// RoundTripperFunc is an inline http.RoundTripper.
type RoundTripperFunc func(*http.Request) (*http.Response, error)
// RoundTrip satisfies RoundTripperFunc.
func (fn RoundTripperFunc) RoundTrip(req *http.Request) (*http.Response, error) {
return fn(req)
}
// BasicAuthRoundTripper sets Basic Authorization header to the given request.
func BasicAuthRoundTripper(username, password string, tripper http.RoundTripper) RoundTripperFunc {
value := fmt.Sprintf("Basic %s", util.Base64Credentials(username, password))
return func(req *http.Request) (*http.Response, error) {
req.Header.Add("Authorization", value)
return tripper.RoundTrip(req)
}
}
// BearerAuthRoundTripper sets Bearer Authorization header to the given request.
func BearerAuthRoundTripper(token string, tripper http.RoundTripper) RoundTripperFunc {
value := fmt.Sprintf("Bearer %s", token)
return func(req *http.Request) (*http.Response, error) {
req.Header.Add("Authorization", value)
return tripper.RoundTrip(req)
}
}
// TokenRoundTripper sets Bearer Authorization header to the given request with a token given by a auth.TokenProvider.
func TokenRoundTripper(p auth.TokenProvider, tripper http.RoundTripper) RoundTripperFunc {
return func(r *http.Request) (*http.Response, error) {
token, err := p.Token(r.Context())
if err != nil {
return nil, err
}
r.Header.Add("Authorization", fmt.Sprintf("Bearer %s", token))
return tripper.RoundTrip(r)
}
}