-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
86 lines (69 loc) · 1.6 KB
/
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package httpclient
import (
"fmt"
"net"
"net/http"
"time"
"github.com/darylnwk/retry"
)
const (
defaultRetryAttempts = 1
defaultTimeout = 30 * time.Second
)
// Client defines a HTTP client
type Client struct {
Client *http.Client
Retryer retry.Retryer
Prehooks []Prehook
Posthooks []Posthook
}
// NewClient initialises a new `Client`
func NewClient(opts ...Option) *Client {
client := &Client{
Client: &http.Client{
Timeout: defaultTimeout,
},
Retryer: retry.Retryer{
Attempts: defaultRetryAttempts,
},
Prehooks: []Prehook{},
Posthooks: []Posthook{},
}
for _, opt := range opts {
opt(client)
}
return client
}
// Do performs HTTP request and returns HTTP response if exists
func (client *Client) Do(request *http.Request) (*http.Response, error) {
var (
response *http.Response
timeout bool
success, errs = client.Retryer.Do(func() error {
var err error
for _, prehook := range client.Prehooks {
prehook(request)
}
response, err = client.Client.Do(request)
for _, posthook := range client.Posthooks {
posthook(response, err)
}
// Retry only on 5xx status codes
if response != nil && response.StatusCode >= http.StatusInternalServerError {
return fmt.Errorf("retrying on %s", response.Status)
}
return err
})
)
if !success {
// Check if last error is a timeout error
if err, ok := errs[len(errs)-1].(net.Error); ok && err.Timeout() {
timeout = true
}
return response, &httpError{
err: fmt.Sprintf("httpclient: request occurred with errors: %s", errs),
timeout: timeout,
}
}
return response, nil
}