-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathrequest.go
158 lines (144 loc) · 3.63 KB
/
request.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
package common
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
"time"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"go.opentelemetry.io/otel/propagation"
)
func init() {
zerolog.TimeFieldFormat = zerolog.TimeFormatUnixMs
log.Logger = zerolog.New(os.Stderr)
log.Logger = log.With().Logger()
}
// HTTPClient allows inserting either *http.Client or mock client.
type HTTPClient interface {
Do(req *http.Request) (*http.Response, error)
}
// HTTPRequest ...
type HTTPRequest struct {
Method string
URL string
Body []byte
Cookies []*http.Cookie
Headers map[string]string
OKCode []int
Unmarshaler func(data []byte, v any) error
}
// HTTPResponse ...
type HTTPResponse struct {
Body []byte
StatusCode int
Headers http.Header
}
// Backoff contains struct for retrying strategy.
type Backoff struct {
// The initial duration.
Duration time.Duration
// The remaining number of iterations in which the duration
// parameter may change. If not positive, the duration is not
// changed.
MaxRetries int
}
// MakeRequest ...
func MakeRequest(
ctx context.Context,
request HTTPRequest,
output interface{},
client HTTPClient,
backoff Backoff,
) (*HTTPResponse, error) {
httpresp := &HTTPResponse{}
if request.Unmarshaler == nil {
request.Unmarshaler = json.Unmarshal
}
propgator := propagation.NewCompositeTextMapPropagator(propagation.TraceContext{}, propagation.Baggage{})
carrier := propagation.MapCarrier{}
propgator.Inject(ctx, carrier)
if request.Headers == nil && len(carrier) > 0 {
request.Headers = make(map[string]string)
}
for k, v := range carrier {
request.Headers[k] = v
}
err := SleepUntil(backoff, func() (bool, error) {
httpreq, err := http.NewRequest(request.Method, request.URL, nil)
if err != nil {
log.Error().
Str("method", request.Method).
Str("url", request.URL).
Str("error", err.Error()).
Msg("request error")
return false, err
}
if len(request.Body) > 0 {
httpreq.Body = io.NopCloser(bytes.NewReader(request.Body))
}
httpreq = httpreq.WithContext(ctx)
for k, v := range request.Headers {
httpreq.Header.Add(k, v)
}
for _, cookie := range request.Cookies {
httpreq.AddCookie(cookie)
}
resp, err := client.Do(httpreq)
if err != nil {
log.Error().
Str("method", request.Method).
Str("url", request.URL).
Str("error", err.Error()).
Msg("do request error")
if errors.Is(err, context.DeadlineExceeded) {
return true, err
}
return false, err
}
defer resp.Body.Close()
httpresp.StatusCode = resp.StatusCode
responseBody, err := io.ReadAll(resp.Body)
if err != nil {
return false, err
}
httpresp.Body = responseBody
httpresp.Headers = resp.Header
if ContainsInteger(request.OKCode, resp.StatusCode) {
if output != nil {
err = request.Unmarshaler(httpresp.Body, &output)
if err != nil {
return true, fmt.Errorf("could not marshal %w", err)
}
}
return true, nil
}
msg := "retrying"
rtn := false
if resp.StatusCode == http.StatusTooManyRequests {
msg = "too many requests"
rtn = true
err = fmt.Errorf("rate limit exceeded")
}
log.Error().
Int("statuscode", resp.StatusCode).
Str("method", request.Method).
Str("url", request.URL).
Str("body", string(responseBody)).
Msg(msg)
return rtn, err
})
return httpresp, err
}
// MockClient is helper client for mock tests.
type MockClient struct {
DoFunc func(req *http.Request) (*http.Response, error)
}
// Do executes the HTTPClient interface Do function.
func (m *MockClient) Do(req *http.Request) (*http.Response, error) {
return m.DoFunc(req)
}