-
Notifications
You must be signed in to change notification settings - Fork 29
/
resty.go
305 lines (243 loc) · 6.17 KB
/
resty.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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
// Package resty HTTP and REST client library with parallel feature
package resty
import (
"context"
"io"
"io/ioutil"
"net"
"net/http"
"sync"
"time"
"github.com/0chain/gosdk/core/sys"
)
// New create a Resty instance.
func New(opts ...Option) *Resty {
r := &Resty{
timeout: DefaultRequestTimeout,
retry: DefaultRetry,
header: make(map[string]string),
}
for _, option := range opts {
option(r)
}
if r.transport == nil {
if DefaultTransport == nil {
DefaultTransport = &http.Transport{
Dial: (&net.Dialer{
Timeout: DefaultDialTimeout,
}).Dial,
TLSHandshakeTimeout: DefaultDialTimeout,
}
}
r.transport = DefaultTransport
}
if r.client == nil {
r.client = CreateClient(r.transport, r.timeout)
}
return r
}
// Client http client
type Client interface {
Do(req *http.Request) (*http.Response, error)
}
// Handle handler of http response
type Handle func(req *http.Request, resp *http.Response, respBody []byte, cf context.CancelFunc, err error) error
// Option set restry option
type Option func(*Resty)
// Resty HTTP and REST client library with parallel feature
type Resty struct {
ctx context.Context
cancelFunc context.CancelFunc
qty int
done chan Result
transport *http.Transport
client Client
handle Handle
requestInterceptor func(req *http.Request) error
timeout time.Duration
retry int
header map[string]string
}
// Then callback for http response
func (r *Resty) Then(fn Handle) *Resty {
if r == nil {
return r
}
r.handle = fn
return r
}
// DoGet execute http requests with GET method in parallel
func (r *Resty) DoGet(ctx context.Context, urls ...string) *Resty {
return r.Do(ctx, http.MethodGet, nil, urls...)
}
// DoPost execute http requests with POST method in parallel
func (r *Resty) DoPost(ctx context.Context, body io.Reader, urls ...string) *Resty {
return r.Do(ctx, http.MethodPost, body, urls...)
}
// DoPut execute http requests with PUT method in parallel
func (r *Resty) DoPut(ctx context.Context, body io.Reader, urls ...string) *Resty {
return r.Do(ctx, http.MethodPut, body, urls...)
}
// DoDelete execute http requests with DELETE method in parallel
func (r *Resty) DoDelete(ctx context.Context, urls ...string) *Resty {
return r.Do(ctx, http.MethodDelete, nil, urls...)
}
func (r *Resty) Do(ctx context.Context, method string, body io.Reader, urls ...string) *Resty {
r.ctx, r.cancelFunc = context.WithCancel(ctx)
r.qty = len(urls)
r.done = make(chan Result, r.qty)
var bodyReader io.Reader = body
for _, url := range urls {
req, err := http.NewRequest(method, url, bodyReader)
if err != nil {
r.done <- Result{Request: req, Response: nil, Err: err}
continue
}
for key, value := range r.header {
req.Header.Set(key, value)
}
//reuse http connection if it is possible
req.Header.Set("Connection", "keep-alive")
if r.requestInterceptor != nil {
if err := r.requestInterceptor(req); err != nil {
r.done <- Result{Request: req, Response: nil, Err: err}
continue
}
}
go r.httpDo(req.WithContext(r.ctx))
}
return r
}
func (r *Resty) httpDo(req *http.Request) {
wg := &sync.WaitGroup{}
wg.Add(1)
go func(request *http.Request) {
var resp *http.Response
var err error
if r.retry > 0 {
for i := 1; ; i++ {
var bodyCopy io.ReadCloser
if (request.Method == http.MethodPost || request.Method == http.MethodPut) && request.Body != nil {
// clone io.ReadCloser to fix retry issue https://github.com/golang/go/issues/36095
bodyCopy, _ = request.GetBody() //nolint: errcheck
}
resp, err = r.client.Do(request)
//success: 200,201,202,204
if resp != nil && (resp.StatusCode == http.StatusOK ||
resp.StatusCode == http.StatusCreated ||
resp.StatusCode == http.StatusAccepted ||
resp.StatusCode == http.StatusNoContent) {
break
}
// close body ReadClose to release resource before retrying it
if resp != nil && resp.Body != nil {
// don't close it if it is latest retry
if i < r.retry {
resp.Body.Close()
}
}
if i == r.retry {
break
}
if resp != nil && resp.StatusCode == http.StatusTooManyRequests {
sys.Sleep(1 * time.Second)
}
if (request.Method == http.MethodPost || request.Method == http.MethodPut) && request.Body != nil {
request.Body = bodyCopy
}
}
} else {
resp, err = r.client.Do(request.WithContext(r.ctx))
}
result := Result{Request: request, Response: resp, Err: err}
if resp != nil {
// read and close body to reuse http connection
buf, err := ioutil.ReadAll(resp.Body)
if err != nil {
result.Err = err
} else {
resp.Body.Close() //nolint: errcheck
result.ResponseBody = buf
}
}
r.done <- result
wg.Done()
}(req)
wg.Wait()
}
// Wait wait all of requests to done
func (r *Resty) Wait() []error {
defer func() {
// call cancelFunc, avoid to memory leak issue
if r.cancelFunc != nil {
r.cancelFunc()
}
}()
errs := make([]error, 0, r.qty)
done := 0
// no urls
if r.qty == 0 {
return errs
}
for {
select {
case <-r.ctx.Done():
return errs
case result := <-r.done:
if r.handle != nil {
err := r.handle(result.Request, result.Response, result.ResponseBody, r.cancelFunc, result.Err)
if err != nil {
errs = append(errs, err)
}
} else {
if result.Err != nil {
errs = append(errs, result.Err)
}
}
}
done++
if done >= r.qty {
return errs
}
}
}
// First successful result or errors
func (r *Resty) First() []error {
defer func() {
// call cancelFunc, avoid to memory leak issue
if r.cancelFunc != nil {
r.cancelFunc()
}
}()
errs := make([]error, 0, r.qty)
done := 0
// no urls
if r.qty == 0 {
return errs
}
for {
select {
case <-r.ctx.Done():
return errs
case result := <-r.done:
if r.handle != nil {
err := r.handle(result.Request, result.Response, result.ResponseBody, r.cancelFunc, result.Err)
if err != nil {
errs = append(errs, err)
} else {
return nil
}
} else {
if result.Err != nil {
errs = append(errs, result.Err)
} else {
return nil
}
}
}
done++
if done >= r.qty {
return errs
}
}
}