-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.go
60 lines (46 loc) · 1.29 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
package rhttp
import (
"context"
"errors"
"net/http"
"github.com/hashicorp/go-retryablehttp"
)
var ErrHttpMovedPermanently = errors.New("moved permanently")
type ClientOption func(*retryablehttp.Client)
func WithErrorIfMovedPermanently() ClientOption {
return func(c *retryablehttp.Client) {
c.HTTPClient.CheckRedirect = func(req *http.Request, via []*http.Request) error {
// default behavior
if len(via) >= 10 {
return errors.New("stopped after 10 redirects")
}
if req.Response.StatusCode == http.StatusMovedPermanently {
return ErrHttpMovedPermanently
}
return nil
}
c.CheckRetry = func(ctx context.Context, resp *http.Response, err error) (bool, error) {
if resp != nil && resp.StatusCode == http.StatusMovedPermanently {
return false, err
}
return retryablehttp.DefaultRetryPolicy(ctx, resp, err)
}
}
}
func WithLogger(logger interface{}) ClientOption {
return func(c *retryablehttp.Client) {
c.Logger = logger
}
}
func WithPassthroughErrorHandler() ClientOption {
return func(c *retryablehttp.Client) {
c.ErrorHandler = retryablehttp.PassthroughErrorHandler
}
}
func NewClient(opts ...ClientOption) *retryablehttp.Client {
retryClient := retryablehttp.NewClient()
for _, opt := range opts {
opt(retryClient)
}
return retryClient
}