-
Notifications
You must be signed in to change notification settings - Fork 160
/
delay_based_on_error_test.go
84 lines (70 loc) · 1.74 KB
/
delay_based_on_error_test.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
// This test delay is based on kind of error
// e.g. HTTP response [Retry-After](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After)
package retry_test
import (
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/avast/retry-go/v4"
"github.com/stretchr/testify/assert"
)
type RetryAfterError struct {
response http.Response
}
func (err RetryAfterError) Error() string {
return fmt.Sprintf(
"Request to %s fail %s (%d)",
err.response.Request.RequestURI,
err.response.Status,
err.response.StatusCode,
)
}
type SomeOtherError struct {
err string
retryAfter time.Duration
}
func (err SomeOtherError) Error() string {
return err.err
}
func TestCustomRetryFunctionBasedOnKindOfError(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "hello")
}))
defer ts.Close()
var body []byte
err := retry.Do(
func() error {
resp, err := http.Get(ts.URL)
if err == nil {
defer func() {
if err := resp.Body.Close(); err != nil {
panic(err)
}
}()
body, err = ioutil.ReadAll(resp.Body)
}
return err
},
retry.DelayType(func(n uint, err error, config *retry.Config) time.Duration {
switch e := err.(type) {
case RetryAfterError:
if t, err := parseRetryAfter(e.response.Header.Get("Retry-After")); err == nil {
return time.Until(t)
}
case SomeOtherError:
return e.retryAfter
}
//default is backoffdelay
return retry.BackOffDelay(n, err, config)
}),
)
assert.NoError(t, err)
assert.NotEmpty(t, body)
}
// use https://github.com/aereal/go-httpretryafter instead
func parseRetryAfter(_ string) (time.Time, error) {
return time.Now().Add(1 * time.Second), nil
}