/
policy.go
65 lines (50 loc) · 1.51 KB
/
policy.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
package httpx
import (
"context"
"fmt"
"io"
"net/http"
"github.com/hashicorp/go-retryablehttp"
)
type RetryCodesType string
const RetryCodesValue RetryCodesType = "retryCodeValue"
var ResponseErrLimit int64 = 1024
type Retry struct {
DisableRetry bool
DisabledStatusCodes []int
EnabledStatusCodes []int
}
// RetryPolicy provides a default callback for Client.CheckRetry, which
// will retry on connection errors and server errors.
func RetryPolicy(ctx context.Context, resp *http.Response, err error) (bool, error) {
// do not retry on context.Canceled or context.DeadlineExceeded
if ctx.Err() != nil {
return false, ctx.Err()
}
retryCodes, _ := ctx.Value(RetryCodesValue).(*Retry)
if retryCodes != nil && retryCodes.DisableRetry {
return false, nil
}
if retryCodes != nil {
for _, disabledStatusCode := range retryCodes.DisabledStatusCodes {
if resp.StatusCode == disabledStatusCode {
return false, nil
}
}
for _, enabledStatusCode := range retryCodes.EnabledStatusCodes {
if resp.StatusCode == enabledStatusCode {
return true, fmt.Errorf("force retried HTTP status %s: [%s]", resp.Status, AddSomeResponse(resp))
}
}
}
v, err := retryablehttp.ErrorPropagatedRetryPolicy(ctx, resp, err)
if v && err != nil {
err = fmt.Errorf("%w: [%s]", err, AddSomeResponse(resp))
}
return v, err
}
// AddSomeResponse not close body, retry library draining it.
func AddSomeResponse(resp *http.Response) []byte {
v, _ := io.ReadAll(io.LimitReader(resp.Body, ResponseErrLimit))
return v
}