-
Notifications
You must be signed in to change notification settings - Fork 0
/
req.go
411 lines (375 loc) · 9.35 KB
/
req.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
package req
import (
"bytes"
"compress/gzip"
"encoding/json"
"encoding/xml"
"errors"
"fmt"
"io"
"io/ioutil"
"mime/multipart"
"net/http"
"net/textproto"
"net/url"
"regexp"
"strconv"
"strings"
"time"
)
// default *Req
var std = New()
// flags to decide which part can be outputed
const (
LreqHead = 1 << iota // output request head (request line and request header)
LreqBody // output request body
LrespHead // output response head (response line and response header)
LrespBody // output response body
Lcost // output time costed by the request
LstdFlags = LreqHead | LreqBody | LrespHead | LrespBody
)
// Req is a convenient client for initiating requests
type Req struct {
client *http.Client
jsonEncOpts *jsonEncOpts
xmlEncOpts *xmlEncOpts
flag int
}
// New create a new *Req
func New() *Req {
return &Req{flag: LstdFlags}
}
var regTextContentType = regexp.MustCompile("text|xml|json|javascript|charset|java")
// Do execute a http request with sepecify method and url,
// and it can also have some optional params, depending on your needs.
func (r *Req) Do(method, rawurl string, v ...interface{}) (resp *Resp, err error) {
if rawurl == "" {
return nil, errors.New("req: url not specified")
}
req := &http.Request{
Method: method,
Header: make(http.Header),
Proto: "HTTP/1.1",
ProtoMajor: 1,
ProtoMinor: 1,
}
resp = &Resp{req: req, r: r}
handleBody := func(data []byte, contentType string) {
resp.reqBody = data
req.Body = resp.getReqBody()
req.ContentLength = int64(len(resp.reqBody))
if contentType != "" && req.Header.Get("Content-Type") == "" {
req.Header.Set("Content-Type", contentType)
}
}
var formParam []Param
var queryParam []QueryParam
var file []FileUpload
for _, p := range v {
switch t := p.(type) {
case Header:
for key, value := range t {
req.Header.Add(key, value)
}
case http.Header:
req.Header = t
case io.Reader:
var rc io.ReadCloser
if trc, ok := t.(io.ReadCloser); ok {
rc = trc
} else {
rc = ioutil.NopCloser(t)
}
req.Body = bodyWrapper{
ReadCloser: rc,
limit: 102400,
}
bs, err := ioutil.ReadAll(t)
if err != nil {
return nil, err
}
handleBody(bs, "")
if rc, ok := t.(io.ReadCloser); ok {
rc.Close()
}
case *bodyJson:
var data []byte
if r.jsonEncOpts != nil {
opts := r.jsonEncOpts
var buf bytes.Buffer
enc := json.NewEncoder(&buf)
enc.SetIndent(opts.indentPrefix, opts.indentValue)
enc.SetEscapeHTML(opts.escapeHTML)
err = enc.Encode(t.v)
if err != nil {
return nil, err
}
data = buf.Bytes()
} else {
data, err = json.Marshal(t.v)
if err != nil {
return nil, err
}
}
handleBody(data, "application/json; charset=UTF-8")
case *bodyXml:
var data []byte
if r.xmlEncOpts != nil {
opts := r.xmlEncOpts
var buf bytes.Buffer
enc := xml.NewEncoder(&buf)
enc.Indent(opts.prefix, opts.indent)
err = enc.Encode(t.v)
if err != nil {
return nil, err
}
data = buf.Bytes()
} else {
data, err = xml.Marshal(t.v)
if err != nil {
return nil, err
}
}
handleBody(data, "application/xml; charset=UTF-8")
case Param:
if method == "GET" {
queryParam = append(queryParam, QueryParam(t))
} else {
formParam = append(formParam, t)
}
case QueryParam:
queryParam = append(queryParam, t)
case string:
handleBody([]byte(t), "")
case []byte:
handleBody(t, "")
case *http.Client:
resp.client = t
case FileUpload:
file = append(file, t)
case []FileUpload:
if file == nil {
file = make([]FileUpload, 0)
}
file = append(file, t...)
case *http.Cookie:
req.AddCookie(t)
case Host:
req.Host = string(t)
case error:
err = t
return
}
}
if len(file) > 0 && (req.Method == "POST" || req.Method == "PUT") {
r.upload(resp, file, formParam)
} else if len(formParam) > 0 {
if req.Body != nil {
return nil, errors.New("req: can not set both body and params")
}
params := make(url.Values)
for _, p := range formParam {
for key, value := range p {
params.Add(key, value)
}
}
paramStr := params.Encode()
handleBody([]byte(paramStr), "application/x-www-form-urlencoded; charset=UTF-8")
}
if len(queryParam) > 0 {
params := make(url.Values)
for _, p := range queryParam {
for key, value := range p {
params.Add(key, value)
}
}
paramStr := params.Encode()
if strings.IndexByte(rawurl, '?') == -1 {
rawurl = rawurl + "?" + paramStr
} else {
rawurl = rawurl + "&" + paramStr
}
}
u, err := url.Parse(rawurl)
if err != nil {
return nil, err
}
req.URL = u
if resp.client == nil {
resp.client = r.Client()
}
now := time.Now()
response, err := resp.client.Do(req)
resp.cost = time.Since(now)
if err != nil {
return
}
resp.resp = response
ct := response.Header.Get("Content-Type")
if ct == "" || regTextContentType.MatchString(ct) { // text
defer response.Body.Close()
var reader io.Reader
if _, ok := resp.client.Transport.(*http.Transport); ok && response.Header.Get("Content-Encoding") == "gzip" && req.Header.Get("Accept-Encoding") != "" {
reader, err = gzip.NewReader(response.Body)
if err != nil {
return nil, err
}
} else {
reader = response.Body
}
respBody, err := ioutil.ReadAll(reader)
if err != nil {
return resp, err
}
resp.respBody = respBody
}
if Debug {
fmt.Println(resp.dump())
}
return
}
type bodyWrapper struct {
io.ReadCloser
buf bytes.Buffer
limit int
}
func (b bodyWrapper) Read(p []byte) (n int, err error) {
n, err = b.ReadCloser.Read(p)
if left := b.limit - b.buf.Len(); left > 0 && n > 0 {
if n <= left {
b.buf.Write(p[:n])
} else {
b.buf.Write(p[:left])
}
}
return
}
type dummyMultipart struct {
buf bytes.Buffer
w *multipart.Writer
}
func (d *dummyMultipart) WriteField(fieldname, value string) error {
h := make(textproto.MIMEHeader)
h.Set("Content-Disposition",
fmt.Sprintf(`form-data; name="%s"`, fieldname))
p, err := d.w.CreatePart(h)
if err != nil {
return err
}
_, err = p.Write([]byte(value))
return err
}
func (d *dummyMultipart) WriteFile(fieldname, filename string) error {
h := make(textproto.MIMEHeader)
h.Set("Content-Disposition",
fmt.Sprintf(`form-data; name="%s"; filename="%s"`,
fieldname, filename))
h.Set("Content-Type", "application/octet-stream")
p, err := d.w.CreatePart(h)
if err != nil {
return err
}
_, err = p.Write([]byte("******"))
return err
}
func newDummyMultipart() *dummyMultipart {
d := new(dummyMultipart)
d.w = multipart.NewWriter(&d.buf)
return d
}
func (r *Req) upload(resp *Resp, file []FileUpload, param []Param) {
pr, pw := io.Pipe()
bodyWriter := multipart.NewWriter(pw)
d := newDummyMultipart()
go func() {
for _, p := range param {
for key, value := range p {
bodyWriter.WriteField(key, value)
d.WriteField(key, value)
}
}
i := 0
for _, f := range file {
if f.FieldName == "" {
i++
f.FieldName = "file" + strconv.Itoa(i)
}
fileWriter, err := bodyWriter.CreateFormFile(f.FieldName, f.FileName)
if err != nil {
return
}
//iocopy
_, err = io.Copy(fileWriter, f.File)
if err != nil {
return
}
f.File.Close()
d.WriteFile(f.FieldName, f.FileName)
}
bodyWriter.Close()
pw.Close()
resp.reqBody = d.buf.Bytes()
}()
resp.req.Header.Set("Content-Type", bodyWriter.FormDataContentType())
resp.req.Body = ioutil.NopCloser(pr)
}
// Get execute a http GET request
func (r *Req) Get(url string, v ...interface{}) (*Resp, error) {
return r.Do("GET", url, v...)
}
// Post execute a http POST request
func (r *Req) Post(url string, v ...interface{}) (*Resp, error) {
return r.Do("POST", url, v...)
}
// Put execute a http PUT request
func (r *Req) Put(url string, v ...interface{}) (*Resp, error) {
return r.Do("PUT", url, v...)
}
// Patch execute a http PATCH request
func (r *Req) Patch(url string, v ...interface{}) (*Resp, error) {
return r.Do("PATCH", url, v...)
}
// Delete execute a http DELETE request
func (r *Req) Delete(url string, v ...interface{}) (*Resp, error) {
return r.Do("DELETE", url, v...)
}
// Head execute a http HEAD request
func (r *Req) Head(url string, v ...interface{}) (*Resp, error) {
return r.Do("HEAD", url, v...)
}
// Options execute a http OPTIONS request
func (r *Req) Options(url string, v ...interface{}) (*Resp, error) {
return r.Do("OPTIONS", url, v...)
}
// Get execute a http GET request
func Get(url string, v ...interface{}) (*Resp, error) {
return std.Get(url, v...)
}
// Post execute a http POST request
func Post(url string, v ...interface{}) (*Resp, error) {
return std.Post(url, v...)
}
// Put execute a http PUT request
func Put(url string, v ...interface{}) (*Resp, error) {
return std.Put(url, v...)
}
// Head execute a http HEAD request
func Head(url string, v ...interface{}) (*Resp, error) {
return std.Head(url, v...)
}
// Options execute a http OPTIONS request
func Options(url string, v ...interface{}) (*Resp, error) {
return std.Options(url, v...)
}
// Delete execute a http DELETE request
func Delete(url string, v ...interface{}) (*Resp, error) {
return std.Delete(url, v...)
}
// Patch execute a http PATCH request
func Patch(url string, v ...interface{}) (*Resp, error) {
return std.Patch(url, v...)
}
// Do execute request.
func Do(method, url string, v ...interface{}) (*Resp, error) {
return std.Do(method, url, v...)
}