-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathretry.go
61 lines (51 loc) · 1.39 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
60
61
package rester
import (
"fmt"
"github.com/cenkalti/backoff/v4"
"github.com/pkg/errors"
"net/http"
"time"
)
type Requester struct {
requestFunc RequestFunc
url string
body string
}
type RequestFunc func() (*http.Response, error)
var ErrRequestNotComplete = errors.New("request not complete")
func (r *Requester) Once() (*http.Response, error) {
resp, err := r.requestFunc()
return resp, err
}
func (r *Requester) WithConstantRetry(timeOut int) {
retryFunc := func() error {
res, err := r.requestFunc()
if err != nil {
return err
}
if err == ErrRequestNotComplete || HttpCodeForRetry(res.StatusCode) {
return ErrRequestNotComplete
}
return nil
}
backoff.Retry(retryFunc, backoff.NewConstantBackOff(time.Duration(timeOut)*time.Second))
}
func (r *Requester) WithExponentialRetry(timeOut int) (respReturn *http.Response, err error) {
reTryCount := -1
retryFunc := func() error {
reTryCount++
res, err := r.requestFunc()
if err == ErrRequestNotComplete {
return ErrRequestNotComplete
} else if HttpCodeForRetry(res.StatusCode) {
err = errors.New(fmt.Sprintf("retriable resp status: %d", res.StatusCode))
return ErrRequestNotComplete
}
respReturn, err = res, err
return err
}
backOffPolicy := backoff.NewExponentialBackOff()
backOffPolicy.MaxElapsedTime = time.Duration(timeOut) * time.Second
backoff.Retry(retryFunc, backOffPolicy)
return
}