/
request.go
405 lines (361 loc) · 8.67 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
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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
// Copyright (c) 2021 Terminus, Inc.
//
// This program is free software: you can use, redistribute, and/or modify
// it under the terms of the GNU Affero General Public License, version 3
// or later ("AGPL"), as published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package httpclient
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"mime/multipart"
"net"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"time"
"github.com/pkg/errors"
"github.com/erda-project/erda-sourcecov/agent/pkg/httpclient/customhttp"
)
type Request struct {
path string
header map[string]string
cookie []*http.Cookie
params url.Values
body io.Reader
err error
method string
host string
proto string
cli *http.Client
internal *http.Request
option *Option
tracer Tracer
// retry
retryOption RetryOption
}
type AfterDo struct{ *Request }
type RetryFn func() (*http.Response, error)
type MultipartItem struct {
Reader io.ReadCloser
// Filename 当 Reader 为 *os.File 时,该值在 Content-Disposition 中生效;默认取 *os.File 的 baseName
// Content-Disposition: form-data; name=${fieldName}; filename=${Filename}
// +optional
Filename string
}
const (
MAX_RETRY_TIMES_FOR_TIMEOUT = 2
)
func (r *Request) Do() AfterDo {
if r.err != nil {
return AfterDo{r}
}
if r.host == "" {
r.err = errors.New("not found host")
return AfterDo{r}
}
if strings.HasPrefix(r.host, "https://") {
r.proto = "https"
r.host = strings.TrimPrefix(r.host, "https://")
} else if strings.HasPrefix(r.host, "http://") {
r.proto = "http"
r.host = strings.TrimPrefix(r.host, "http://")
} else if strings.HasPrefix(r.host, "inet://") {
r.proto = "inet"
r.host = strings.TrimPrefix(r.host, "inet://")
}
_url := fmt.Sprintf("%s://%s%s", r.proto, r.host, r.path)
if len(r.params) > 0 {
_url += "?" + r.params.Encode()
}
req, err := customhttp.NewRequest(r.method, _url, r.body)
if err != nil {
r.err = err
return AfterDo{r}
}
for k, v := range r.header {
req.Header.Set(k, v)
}
for _, v := range r.cookie {
req.AddCookie(v)
}
if len(req.Header.Get("Accept")) == 0 {
req.Header.Set("Accept", "application/json, */*")
}
r.internal = req
return AfterDo{r}
}
func (r *Request) GetUrl() string {
return fmt.Sprintf("%s://%s%s?%s", r.proto, r.host, r.path, r.params.Encode())
}
// 构造2个一样的 request
func dupRequest(req *http.Request) (*http.Request, *http.Request, error) {
var bodybuf []byte
if req.Body != nil {
var err error
bodybuf, err = ioutil.ReadAll(req.Body)
if err != nil {
return nil, nil, err
}
}
dupbody1 := bytes.NewReader(bodybuf)
dupbody2 := bytes.NewReader(bodybuf)
req1, err := http.NewRequest(req.Method, req.URL.String(), dupbody1)
if err != nil {
return nil, nil, err
}
req2, err := http.NewRequest(req.Method, req.URL.String(), dupbody2)
if err != nil {
return nil, nil, err
}
req1.Header = req.Header
req2.Header = req.Header
return req1, req2, nil
}
func doRequest(r AfterDo) (*http.Response, error) {
if r.err != nil {
return nil, r.err
}
if r.tracer != nil {
r.tracer.TraceRequest(r.internal)
}
var resp *http.Response
var err error
f := func() {
fn := func() (*http.Response, error) {
req1, req2, err := dupRequest(r.internal)
if err != nil {
return nil, err
}
r.internal = req1
return r.cli.Do(req2)
}
if strings.Index(r.internal.Header.Get("Content-Type"), "multipart/form-data;") == 0 {
//上传文件不复制request重试,防止OOM
resp, err = r.cli.Do(r.internal)
} else {
resp, err = retry(r, fn)
}
}
if r.option != nil && r.option.loadingPrint {
if r.option.loadingDesc != "" {
Loading(r.option.loadingDesc, f, true, false)
} else {
Loading(r.path, f, true, false)
}
} else {
f()
}
if err != nil {
return nil, err
}
if r.tracer != nil {
r.tracer.TraceResponse(resp)
}
return resp, nil
}
func (r AfterDo) RAW() (*http.Response, error) {
return doRequest(r)
}
func (r AfterDo) JSON(o interface{}) (*Response, error) {
resp, err := doRequest(r)
if err != nil {
return nil, err
}
defer resp.Body.Close()
// check content-type before decode body
contentType := resp.Header.Get("Content-Type")
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if len(contentType) > 0 && !contentTypeIsJson(contentType) {
return &Response{
body: body,
internal: resp,
}, nil
}
if err := json.Unmarshal(body, o); err != nil {
return nil, fmt.Errorf("failed to Unmarshal JSON, err:%s,body :%s", err, string(body))
}
return &Response{
body: body,
internal: resp,
}, nil
}
// 适用于a) 如果成功,不关心body内容及其结构体;
// 并且b) 如果失败,需要把body内容封装进error里返回给上层定位错误
func (r AfterDo) Body(b *bytes.Buffer) (*Response, error) {
resp, err := doRequest(r)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if _, err = io.Copy(b, resp.Body); err != nil {
return nil, err
}
return &Response{
internal: resp,
}, nil
}
// StreamBody 返回 response body, 用于流式读取。
// 场景:k8s & marathon event.
// 注意:使用完后,需要自己 close body.
func (r AfterDo) StreamBody() (io.ReadCloser, *Response, error) {
resp, err := doRequest(r)
if err != nil {
return nil, nil, err
}
return resp.Body, &Response{
internal: resp,
}, nil
}
func (r AfterDo) DiscardBody() (*Response, error) {
resp, err := doRequest(r)
if err != nil {
return nil, err
}
defer resp.Body.Close()
io.Copy(ioutil.Discard, resp.Body)
return &Response{
internal: resp,
}, nil
}
func (r *Request) Path(path string) *Request {
r.path = path
return r
}
func (r *Request) Param(k, v string) *Request {
if r.params == nil {
r.params = make(url.Values)
}
r.params.Add(k, v)
return r
}
func (r *Request) Params(kvs url.Values) *Request {
if r.params == nil {
r.params = make(url.Values)
}
for k, v := range kvs {
r.params[k] = append(r.params[k], v...)
}
return r
}
func (r *Request) JSONBody(o interface{}) *Request {
b, err := json.Marshal(o)
if err != nil {
r.err = err
}
r.body = bytes.NewReader(b)
r.Header("Content-Type", "application/json")
return r
}
func (r *Request) RawBody(body io.Reader) *Request {
r.body = body
return r
}
func (r *Request) FormBody(form url.Values) *Request {
r.body = strings.NewReader(form.Encode())
r.Header("Content-Type", "application/x-www-form-urlencoded")
return r
}
func (r *Request) MultipartFormDataBody(fields map[string]MultipartItem) *Request {
pipeReader, pipeWriter := io.Pipe()
w := multipart.NewWriter(pipeWriter)
go func() {
defer func() {
for _, field := range fields {
field.Reader.Close()
}
}()
for field, item := range fields {
var fw io.Writer
var err error
switch item.Reader.(type) {
case *os.File:
if item.Filename == "" {
item.Filename = filepath.Base(item.Reader.(*os.File).Name())
}
fw, err = w.CreateFormFile(field, item.Filename)
default:
fw, err = w.CreateFormFile(field, item.Filename)
}
if err != nil {
r.err = err
return
}
if _, err := io.Copy(fw, item.Reader); err != nil {
r.err = err
return
}
}
w.Close()
pipeWriter.Close()
}()
r.body = pipeReader
r.Header("Content-Type", w.FormDataContentType())
return r
}
func (r *Request) Header(k, v string) *Request {
r.header[k] = v
return r
}
func (r *Request) Headers(hs http.Header) *Request {
for k, v := range hs {
if len(v) > 0 {
r.header[k] = v[0]
}
}
return r
}
func (r *Request) Cookie(v *http.Cookie) *Request {
r.cookie = append(r.cookie, v)
return r
}
func contentTypeIsJson(contentType string) bool {
return strings.Contains(contentType, "json")
}
func retryIfTimeout(fn RetryFn) (*http.Response, error) {
resp, err := fn()
for i := 0; i < MAX_RETRY_TIMES_FOR_TIMEOUT; i++ {
if nerr, ok := err.(net.Error); ok && nerr.Timeout() {
resp, err = fn()
} else {
break
}
}
return resp, err
}
func retry(r AfterDo, fn RetryFn) (*http.Response, error) {
maxtime := r.retryOption.MaxTime
fns := r.retryOption.Fns
interval := r.retryOption.Interval
var resp *http.Response
var err error
for i := 0; i < maxtime; i++ {
resp, err = retryIfTimeout(fn)
retry := false
for _, fn := range fns {
if fn(r.internal, resp, err) {
retry = true
time.Sleep(time.Duration(interval) * time.Second)
break
}
}
if !retry {
return resp, err
}
}
return resp, err
}