forked from gotsunami/mangopay2-go-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp.go
68 lines (55 loc) · 1.26 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
64
65
66
67
68
package mango
import (
"fmt"
"net/http"
"time"
)
type config struct {
count int
pause time.Duration
statuses httpStatusList
}
type httpStatusList []int
func (s httpStatusList) Consist(status int) bool {
for _, item := range s {
if item == status {
return true
}
}
return false
}
type httpClient interface {
Do(req *http.Request) (*http.Response, error)
}
type httpClientRetryWrap struct {
config config
client httpClient
}
func NewDefaultHTTPClientRetryWrap(client httpClient) *httpClientRetryWrap {
var (
httpRetryDefaultCount = 3
httpRetryDefaultPause = time.Second
httpRetryDefaultStatuses = []int{524} //could consist custom statuses e.g. 524: A timeout occurred from CloudFlare
)
return &httpClientRetryWrap{
config: config{
count: httpRetryDefaultCount,
pause: httpRetryDefaultPause,
statuses: httpRetryDefaultStatuses,
},
client: client,
}
}
func (w *httpClientRetryWrap) do(req *http.Request) (*http.Response, error) {
for i := w.config.count; i > 0; i-- {
resp, err := w.client.Do(req)
if err != nil {
return nil, err
}
if !w.config.statuses.Consist(resp.StatusCode) {
return resp, nil
}
time.Sleep(w.config.pause)
}
return nil, fmt.Errorf("request retrying failed for URL: %s", req.URL)
}