-
Notifications
You must be signed in to change notification settings - Fork 3
/
retry.go
57 lines (43 loc) · 1.04 KB
/
retry.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
package retry
import (
"context"
"errors"
"net/http"
retry "github.com/avast/retry-go/v3"
"github.com/hashicorp/go-retryablehttp"
)
// ErrInvalidStatusCode for http retry.
var ErrInvalidStatusCode = errors.New("invalid status code")
// NewRoundTripper for retry.
func NewRoundTripper(cfg *Config, hrt http.RoundTripper) *RoundTripper {
return &RoundTripper{cfg: cfg, RoundTripper: hrt}
}
// RoundTripper for retry.
type RoundTripper struct {
cfg *Config
http.RoundTripper
}
func (r *RoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
var (
res *http.Response
err error
)
ctx := req.Context()
operation := func() error {
tctx, cancel := context.WithTimeout(ctx, r.cfg.Timeout)
defer cancel()
res, err = r.RoundTripper.RoundTrip(req.WithContext(tctx))
ok, perr := retryablehttp.ErrorPropagatedRetryPolicy(tctx, res, err)
if ok {
if perr != nil {
return perr
}
if err != nil {
return err
}
}
return nil
}
_ = retry.Do(operation, retry.Attempts(r.cfg.Attempts))
return res, err
}