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