-
Notifications
You must be signed in to change notification settings - Fork 5
/
http.go
63 lines (50 loc) · 1.1 KB
/
http.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
54
55
56
57
58
59
60
61
62
63
package hjem
import (
"math"
"net/http"
"time"
)
var DefaultClient http.Client
func init() {
DefaultClient = http.Client{
Transport: &RetryRoundTripper{
next: &DefaultHeadersTripper{
next: http.DefaultTransport,
headers: map[string]string{
"User-Agent": "tpanum/hjem (github.com/tpanum/hjem)",
},
},
maxRetries: 5,
},
}
}
type DefaultHeadersTripper struct {
next http.RoundTripper
headers map[string]string
}
func (t *DefaultHeadersTripper) RoundTrip(req *http.Request) (*http.Response, error) {
for k, v := range t.headers {
req.Header.Add(k, v)
}
return t.next.RoundTrip(req)
}
type RetryRoundTripper struct {
next http.RoundTripper
maxRetries int
}
func (r *RetryRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
var resp *http.Response
var err error
for i := 0; i <= r.maxRetries; i++ {
resp, err = r.next.RoundTrip(req)
if err != nil {
return nil, err
}
if resp.StatusCode != 429 {
return resp, nil
}
backoff := time.Duration(math.Pow(1.5, float64(i))) * time.Second
time.Sleep(backoff)
}
return resp, err
}