-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtransport.go
73 lines (61 loc) · 1.24 KB
/
transport.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
package retry
import (
"bytes"
"errors"
"io/ioutil"
"net/http"
"github.com/cenkalti/backoff/v3"
"github.com/google/uuid"
"github.com/izumin5210/hx"
)
type Transport struct {
parent http.RoundTripper
cond hx.ResponseHandlerCond
bo backoff.BackOff
}
var _ http.RoundTripper = (*Transport)(nil)
func NewTransport(
parent http.RoundTripper,
cond hx.ResponseHandlerCond,
bo backoff.BackOff,
) *Transport {
return &Transport{
parent: parent,
cond: cond,
bo: bo,
}
}
func (t *Transport) RoundTrip(req *http.Request) (resp *http.Response, err error) {
bo := backoff.WithContext(t.bo, req.Context())
bo.Reset()
if req.Body != nil {
var buf bytes.Buffer
_, err := buf.ReadFrom(req.Body)
if err != nil {
return nil, err
}
err = req.Body.Close()
if err != nil {
return nil, err
}
req.Body = ioutil.NopCloser(&buf)
}
setIdempotencyKey(req)
next := t.parent
if next == nil {
next = http.DefaultTransport
}
_ = backoff.Retry(func() error {
resp, err = next.RoundTrip(req)
if t.cond(resp, err) {
return errors.New("retry")
}
return nil
}, bo)
return
}
func setIdempotencyKey(r *http.Request) {
if r.Header.Get("Idempotency-Key") == "" {
r.Header.Set("Idempotency-Key", uuid.New().String())
}
}