-
Notifications
You must be signed in to change notification settings - Fork 5
/
http_client.go
55 lines (45 loc) · 1.18 KB
/
http_client.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
package synthetics
import (
"log"
"net/http"
"time"
)
// RetryableHTTPClient is the interface to an HTTP client that
// supports retries.
type RetryableHTTPClient interface {
Do(func() (*http.Request, error)) (*http.Response, error)
}
// HTTPClient is the interface to an HTTP client.
type HTTPClient interface {
Do(*http.Request) (*http.Response, error)
}
type httpClientWithRetries struct {
client HTTPClient
retries uint
}
func newHTTPClientWithRetries(client HTTPClient, retries uint) *httpClientWithRetries {
return &httpClientWithRetries{client: client, retries: retries}
}
// Do performs a request with retries.
func (h *httpClientWithRetries) Do(reqFunc func() (*http.Request, error)) (*http.Response, error) {
var response *http.Response
for i := uint(0); i < h.retries; i++ {
req, err := reqFunc()
if err != nil {
return nil, err
}
response, err := h.client.Do(req)
if err != nil {
return nil, err
}
if response.StatusCode == http.StatusTooManyRequests {
if i != h.retries-1 {
log.Printf("rate limited by synthetics, sleeping then retrying")
time.Sleep((1 << i) * time.Second)
}
continue
}
return response, nil
}
return response, nil
}