forked from go-auth0/auth0
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
52 lines (46 loc) · 1.17 KB
/
utils.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
package management
import (
"net/http"
"strconv"
"time"
"github.com/PuerkitoBio/rehttp"
)
func wrapRetry(c *http.Client) *http.Client {
if c == nil {
c = http.DefaultClient
}
return &http.Client{
Transport: rehttp.NewTransport(
c.Transport,
func(attempt rehttp.Attempt) bool {
if attempt.Response == nil {
return false
}
return attempt.Response.StatusCode == http.StatusTooManyRequests
},
func(attempt rehttp.Attempt) time.Duration {
resetAt := attempt.Response.Header.Get("X-RateLimit-Reset")
resetAtUnix, err := strconv.ParseInt(resetAt, 10, 64)
if err != nil {
resetAtUnix = time.Now().Add(5 * time.Second).Unix()
}
return time.Unix(resetAtUnix, 0).Sub(time.Now())
},
),
}
}
func wrapUserAgent(c *http.Client) *http.Client {
if c == nil {
c = http.DefaultClient
}
return &http.Client{
Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) {
r.Header.Set("User-Agent", "Go-Auth0-SDK/v0")
return c.Transport.RoundTrip(r)
}),
}
}
type roundTripFunc func(*http.Request) (*http.Response, error)
func (rf roundTripFunc) RoundTrip(r *http.Request) (*http.Response, error) {
return rf(r)
}