/
http.go
515 lines (466 loc) · 13.5 KB
/
http.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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
package easy
import (
"bytes"
"context"
"encoding/xml"
"fmt"
"io"
"io/ioutil"
"log"
"net"
"net/http"
"net/http/httputil"
"net/url"
"regexp"
"strings"
"time"
"github.com/jxskiss/gopkg/internal/unsafeheader"
"github.com/jxskiss/gopkg/json"
)
var (
hdrContentTypeKey = http.CanonicalHeaderKey("Content-Type")
contentTypeJSON = "application/json"
contentTypeXML = "application/xml"
contentTypeForm = "application/x-www-form-urlencoded"
jsonCheck = regexp.MustCompile(`(?i:(application|text)/(json|.*\+json|json\-.*)(;|$))`)
xmlCheck = regexp.MustCompile(`(?i:(application|text)/(xml|.*\+xml)(;|$))`)
)
// SingleJoin joins the given text segments using sep.
// No matter whether a segment begins or ends with sep or not, it
// guarantees that only one sep appears between two segments.
func SingleJoin(sep string, text ...string) string {
if len(text) == 0 {
return ""
}
result := text[0]
for _, next := range text[1:] {
asep := strings.HasSuffix(result, sep)
bsep := strings.HasPrefix(next, sep)
switch {
case asep && bsep:
result += next[len(sep):]
case !asep && !bsep:
result += sep + next
default:
result += next
}
}
return result
}
// SlashJoin joins the given path segments using "/".
// No matter whether a segment begins or ends with "/" or not, it guarantees
// that only one "/" appears between two segments.
func SlashJoin(path ...string) string {
return SingleJoin("/", path...)
}
// JSONToReader converts an json encodeable object to an io.Reader.
// If obj cannot be marshaled as JSON, it reports the error.
func JSONToReader(obj interface{}) (io.Reader, error) {
b, err := json.Marshal(obj)
if err != nil {
return nil, err
}
return bytes.NewBuffer(b), nil
}
// DecodeJSON decodes a json value from r.
func DecodeJSON(r io.Reader, v interface{}) error {
data, err := ioutil.ReadAll(r)
if err != nil {
return err
}
return json.Unmarshal(data, v)
}
// IsJSONType method is to check JSON content type or not.
func IsJSONType(contentType string) bool {
return jsonCheck.MatchString(contentType)
}
// XMLToReader converts an XML encodeable object to an io.Reader.
// If obj cannot be marshaled as XML, it reports the error.
func XMLToReader(obj interface{}) (io.Reader, error) {
b, err := xml.Marshal(obj)
if err != nil {
return nil, err
}
return bytes.NewBuffer(b), nil
}
// DecodeXML decodes a XML value from r.
func DecodeXML(r io.Reader, v interface{}) error {
data, err := ioutil.ReadAll(r)
if err != nil {
return err
}
return xml.Unmarshal(data, v)
}
// IsXMLType method is to check XML content type or not.
func IsXMLType(contentType string) bool {
return xmlCheck.MatchString(contentType)
}
// Request represents a request and options to send with the DoRequest function.
type Request struct {
// Req should be a fully prepared http Request to sent, if not nil,
// the following `Method`, `URL`, `Params`, `JSON`, `XML`, `Form`, `Body`
// will be ignored.
//
// If Req is nil, it will be filled using the following data `Method`,
// `URL`, `Params`, `JSON`, `XML`, `Form`, `Body` to construct the `http.Request`.
//
// When building http body, the priority is JSON > XML > Form > Body.
Req *http.Request
// Method specifies the verb for the http request, it's optional,
// default is "GET".
Method string
// URL specifies the url to make the http request.
// It's required if Req is nil.
URL string
// Params specifies optional params to merge with URL, it must be one of
// the following types:
// - map[string]string
// - map[string][]string
// - map[string]interface{}
// - url.Values
Params interface{}
// JSON specifies optional body data for request which can take body,
// the content-type will be "application/json", it must be one of
// the following types:
// - io.Reader
// - []byte (will be wrapped with bytes.NewReader)
// - string (will be wrapped with strings.NewReader)
// - interface{} (will be marshaled with json.Marshal)
JSON interface{}
// XML specifies optional body data for request which can take body,
// the content-type will be "application/xml", it must be one of
// the following types:
// - io.Reader
// - []byte (will be wrapped with bytes.NewReader)
// - string (will be wrapped with strings.NewReader)
// - interface{} (will be marshaled with xml.Marshal)
XML interface{}
// Form specifies optional body data for request which can take body,
// the content-type will be "application/x-www-form-urlencoded",
// it must be one of the following types:
// - io.Reader
// - []byte (will be wrapped with bytes.NewReader)
// - string (will be wrapped with strings.NewReader)
// - url.Values (will be encoded and wrapped as io.Reader)
// - map[string]string (will be converted to url.Values)
// - map[string][]string (will be converted to url.Values)
// - map[string]interface{} (will be converted to url.Values)
Form interface{}
// Body specifies optional body data for request which can take body,
// the content-type will be detected from the content (may be incorrect),
// it should be one of the following types:
// - io.Reader
// - []byte (will be wrapped with bytes.NewReader)
// - string (will be wrapped with strings.NewReader)
Body interface{}
// Headers will be copied to the request before sent.
//
// If "Content-Type" presents, it will replace the default value
// set by `JSON`, `XML`, `Form`, or `Body`.
Headers map[string]string
// Resp specifies an optional destination to unmarshal the response data.
// if `Unmarshal` is not provided, the header "Content-Type" will be used to
// detect XML content, else `json.Unmarshal` will be used.
Resp interface{}
// Unmarshal specifies an optional function to unmarshal the response data.
Unmarshal func([]byte, interface{}) error
// Context specifies an optional context.Context to use with http request.
Context context.Context
// Timeout specifies an optional timeout of the http request, if
// timeout > 0, the request will be attached an timeout context.Context.
// `Timeout` takes higher priority than `Context`, it both available, only
// `Timeout` takes effect.
Timeout time.Duration
// Client specifies an optional http.Client to do the request, instead of
// the default http client.
Client *http.Client
// DisableRedirect tells the http client don't follow response redirection.
DisableRedirect bool
// DumpRequest makes the http request being logged before sent.
DumpRequest bool
// DumpResponse makes the http response being logged after received.
DumpResponse bool
// RaiseForStatus tells `DoRequest` to report an error if the response
// status code >= 400. The error will be formatted as "unexpected status: <STATUS>".
RaiseForStatus bool
}
func (p *Request) buildClient() *http.Client {
if p.Client == nil && !p.DisableRedirect {
return NoHttp2Client
}
var client = *NoHttp2Client
if p.Client != nil {
client = *p.Client
}
if p.DisableRedirect {
client.CheckRedirect = func(_ *http.Request, _ []*http.Request) error {
return http.ErrUseLastResponse
}
}
return &client
}
func (p *Request) prepareRequest(method string) (err error) {
if p.Req != nil {
return nil
}
reqURL := p.URL
if p.Params != nil {
reqURL, err = mergeQuery(reqURL, p.Params)
if err != nil {
return err
}
}
if method == "" {
method = p.Method
}
if method == "" || method == "GET" {
p.Req, err = http.NewRequest(method, reqURL, nil)
return
}
var body io.Reader
var contentType string
if p.JSON != nil { // JSON
body, err = p.makeBody(p.JSON, json.Marshal)
contentType = contentTypeJSON
} else if p.XML != nil { // XML
body, err = p.makeBody(p.XML, xml.Marshal)
contentType = contentTypeXML
} else if p.Form != nil { // urlencoded form
body, err = p.makeBody(p.Form, marshalForm)
contentType = contentTypeForm
} else if p.Body != nil { // detect content-type from the body data
var bodyBuf []byte
switch data := p.Body.(type) {
case io.Reader:
bodyBuf, err = ioutil.ReadAll(data)
if err != nil {
return err
}
case []byte:
bodyBuf = data
case string:
bodyBuf = unsafeheader.StringToBytes(data)
default:
err = fmt.Errorf("unsupported body data type: %T", data)
return err
}
body = bytes.NewReader(bodyBuf)
if p.Headers[hdrContentTypeKey] == "" {
contentType = http.DetectContentType(bodyBuf)
}
} // else no body data
if err != nil {
return err
}
p.Req, err = http.NewRequest(method, p.URL, body)
if err != nil {
return err
}
if contentType != "" {
p.Req.Header.Set(hdrContentTypeKey, contentType)
}
return
}
func mergeQuery(reqURL string, params interface{}) (string, error) {
parsed, err := url.Parse(reqURL)
if err != nil {
return "", err
}
query, err := url.ParseQuery(parsed.RawQuery)
if err != nil {
return "", err
}
switch params := params.(type) {
case map[string]string:
for k, v := range params {
query.Add(k, v)
}
case map[string][]string:
for k, values := range params {
for _, v := range values {
query.Add(k, v)
}
}
case map[string]interface{}:
for k, v := range params {
switch value := v.(type) {
case string:
query.Add(k, fmt.Sprintf(value))
case []string:
for _, v := range value {
query.Add(k, v)
}
default:
query.Add(k, fmt.Sprint(v))
}
}
case url.Values:
for k, values := range params {
for _, v := range values {
query.Add(k, v)
}
}
default:
err = fmt.Errorf("unsupported params type: %T", params)
return "", err
}
parsed.RawQuery = query.Encode()
return parsed.String(), nil
}
func marshalForm(v interface{}) ([]byte, error) {
var form url.Values
switch data := v.(type) {
case url.Values:
form = data
case map[string][]string:
form = data
case map[string]string:
form = make(url.Values, len(data))
for k, v := range data {
form[k] = []string{v}
}
case map[string]interface{}:
form = make(url.Values, len(data))
for k, v := range data {
switch value := v.(type) {
case string:
form[k] = []string{value}
case []string:
form[k] = value
default:
form[k] = []string{fmt.Sprint(v)}
}
}
}
if form == nil {
err := fmt.Errorf("unsupported form data type: %T", v)
return nil, err
}
encoded := form.Encode()
buf := unsafeheader.StringToBytes(encoded)
return buf, nil
}
type marshalFunc func(interface{}) ([]byte, error)
func (p *Request) makeBody(data interface{}, marshal marshalFunc) (io.Reader, error) {
var body io.Reader
switch x := data.(type) {
case io.Reader:
body = x
case []byte:
body = bytes.NewReader(x)
case string:
body = strings.NewReader(x)
default:
buf, err := marshal(data)
if err != nil {
return nil, err
}
body = bytes.NewReader(buf)
}
return body, nil
}
func (p *Request) prepareHeaders() {
if p.Req == nil {
return
}
for k, v := range p.Headers {
p.Req.Header.Set(k, v)
}
}
// DoRequest is a convenient function to send request and control redirect
// and debug options. If `Request.Resp` is provided, it will be used as
// destination to try to unmarshal the response body.
//
// Trade-off was taken to balance simplicity and convenience of the function.
//
// For more powerful controls of a http request and handy utilities,
// you may take a look at the awesome library `https://github.com/go-resty/resty/`.
func DoRequest(req *Request) (respContent []byte, status int, err error) {
if err = req.prepareRequest(""); err != nil {
return
}
req.prepareHeaders()
httpReq := req.Req
if req.Context != nil {
httpReq = httpReq.WithContext(req.Context)
}
if req.Timeout > 0 {
timeoutCtx, cancel := context.WithTimeout(httpReq.Context(), req.Timeout)
defer cancel()
httpReq = httpReq.WithContext(timeoutCtx)
}
if req.DumpRequest {
var dump []byte
dump, err = httputil.DumpRequestOut(httpReq, true)
if err != nil {
return
}
log.Printf("dump http request:\n%s", dump)
}
httpClient := req.buildClient()
httpResp, err := httpClient.Do(httpReq)
if err != nil {
return
}
defer httpResp.Body.Close()
status = httpResp.StatusCode
if req.DumpResponse {
var dump []byte
dump, err = httputil.DumpResponse(httpResp, true)
if err != nil {
return
}
log.Printf("dump http response:\n%s", dump)
}
respContent, err = ioutil.ReadAll(httpResp.Body)
if err != nil {
return
}
if req.RaiseForStatus {
if httpResp.StatusCode >= 400 {
err = fmt.Errorf("unexpected status: %v", httpResp.Status)
return
}
}
if req.Resp != nil && len(respContent) > 0 {
unmarshal := req.Unmarshal
if unmarshal == nil {
ct := httpResp.Header.Get(hdrContentTypeKey)
if IsXMLType(ct) {
unmarshal = xml.Unmarshal
}
// default: JSON
if unmarshal == nil {
unmarshal = json.Unmarshal
}
}
err = unmarshal(respContent, req.Resp)
if err != nil {
return
}
}
return
}
var zeroDialer net.Dialer
// NoHttp2Client disables HTTP/2 feature by specifying a custom DialContext
// function, otherwise it behaves exactly same with http.NoHttp2Client.
//
// HTTP/2 support in golang has many problematic corner cases where dead
// connections would be kept and used in connection pools. See:
//
// https://github.com/golang/go/issues/32388
// https://github.com/golang/go/issues/39337
// https://github.com/golang/go/issues/39750
//
// The deadlock reported by issue 32388 is observed in our production deployment,
// thus we disable HTTP/2 to help to get a better sleep.
var NoHttp2Client = &http.Client{
Transport: &http.Transport{
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
return zeroDialer.DialContext(ctx, network, addr)
},
Dial: func(network, addr string) (net.Conn, error) {
return zeroDialer.Dial(network, addr)
},
},
}