-
Notifications
You must be signed in to change notification settings - Fork 2
/
retry.go
46 lines (37 loc) · 1.02 KB
/
retry.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
package acpclient
import (
"context"
"net/http"
"sync"
"golang.org/x/oauth2"
"golang.org/x/oauth2/clientcredentials"
)
type Authenticator struct {
transport *http.Client
client *http.Client
config clientcredentials.Config
mutex sync.Mutex
}
func NewAuthenticator(config clientcredentials.Config, client *http.Client) *http.Client {
return &http.Client{
Transport: &Authenticator{
transport: config.Client(context.WithValue(context.Background(), oauth2.HTTPClient, client)),
config: config,
client: client,
},
}
}
func (t *Authenticator) RoundTrip(req *http.Request) (res *http.Response, err error) {
if res, err = t.transport.Do(req); err != nil {
return res, err
} else if res.StatusCode == http.StatusUnauthorized || res.StatusCode == http.StatusForbidden {
t.renew()
return t.transport.Do(req)
}
return res, nil
}
func (t *Authenticator) renew() {
t.mutex.Lock()
defer t.mutex.Unlock()
t.transport = t.config.Client(context.WithValue(context.Background(), oauth2.HTTPClient, t.client))
}