-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathmain.go
653 lines (523 loc) · 16.4 KB
/
main.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
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
// Copyright (c) 2013-2014 José Carlos Nieto, https://menteslibres.net/xiam
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// The rest package helps you creating HTTP clients for APIs with Go.
package rest
import (
"bytes"
"compress/gzip"
"crypto/tls"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"mime/multipart"
"net/http"
"net/http/cookiejar"
"net/url"
"os"
"path"
"reflect"
"strconv"
"strings"
)
const debugEnv = `REST_DEBUG`
const (
debugLevelSilence = iota
debugLevelVerbose
)
var debugLevel = debugLevelSilence
var (
ioReadCloserType = reflect.TypeOf((*io.ReadCloser)(nil)).Elem()
bytesBufferType = reflect.TypeOf((**bytes.Buffer)(nil)).Elem()
restResponseType = reflect.TypeOf((*Response)(nil)).Elem()
)
// Response can be used as a response value, useful when you need to work with
// headers, status codes and such.
type Response struct {
Status string
StatusCode int
Proto string
ProtoMajor int
ProtoMinor int
ContentLength int64
http.Header
Body []byte
}
// File can be used to represent a file that you'll later upload within a
// multipart request.
type File struct {
Name string
io.Reader
}
type FileMap map[string][]File
// MultipartMessage struct for multipart requests, you can't generate a
// MultipartMessage directly, use rest.NewMultipartMessage() instead.
type MultipartMessage struct {
contentType string
buf io.Reader
}
// Client is useful in case you need to communicate with an API and you'd like
// to use the same prefix for all of your requests or in scenarios where it
// would be handy to keep a session cookie.
type Client struct {
// These headers will be added in every request.
Header http.Header
// String to be added at the begining of every URL in Get(), Post(), Put()
// and Delete() methods.
Prefix string
// Jar to store cookies.
CookieJar *cookiejar.Jar
// Optional tls transport
TlsTransport *http.Transport
}
// DefaulClient is the default client used on top level functions like
// rest.Get(), rest.Post(), rest.Delete() and rest.Put().
var DefaultClient = new(Client)
func debugLevelEnabled(level int) bool {
if level <= debugLevel {
return true
}
return false
}
func init() {
// If the enviroment variable REST_DEBUG is present, we enable verbose
// logging.
debugSetting := os.Getenv(debugEnv)
debugLevel, _ = strconv.Atoi(debugSetting)
}
// New creates a new client, in all following GET, POST, PUT and DELETE
// requests given paths will be prefixed with the given client's prefix value.
func New(prefix string) (*Client, error) {
var err error
if _, err = url.Parse(prefix); err != nil {
return nil, fmt.Errorf(ErrInvalidPrefix.Error(), err.Error())
}
self := new(Client)
self.Prefix = strings.TrimRight(prefix, "/") + "/"
self.Header = http.Header{}
if self.CookieJar, err = cookiejar.New(nil); err != nil {
return nil, err
}
return self, nil
}
func NewTLS(prefix string, tlsClient *tls.Config) (*Client, error) {
client, err := New(prefix)
if err != nil {
return client, err
}
client.TlsTransport = &http.Transport{
TLSClientConfig: tlsClient,
}
return client, err
}
// Taken from net/http
func basicAuth(username, password string) string {
auth := username + ":" + password
return base64.StdEncoding.EncodeToString([]byte(auth))
}
// Sets the request's basic authorization header to be used in all requests.
func (self *Client) SetBasicAuth(username string, password string) {
self.Header.Set("Authorization", "Basic "+basicAuth(username, password))
}
func (self *Client) newMultipartRequest(dst interface{}, method string, addr *url.URL, body *MultipartMessage) error {
var res *http.Response
var req *http.Request
var err error
if body == nil {
return ErrCouldNotCreateMultipart
}
if req, err = http.NewRequest(method, addr.String(), body.buf); err != nil {
return err
}
req.Header.Set("Content-Type", body.contentType)
if res, err = self.do(req); err != nil {
return err
}
if err = self.handleResponse(dst, res); err != nil {
return err
}
return nil
}
func (self *Client) newRequest(dst interface{}, method string, addr *url.URL, body *strings.Reader) error {
var res *http.Response
var req *http.Request
var err error
if body == nil {
if req, err = http.NewRequest(method, addr.String(), nil); err != nil {
return err
}
} else {
if req, err = http.NewRequest(method, addr.String(), body); err != nil {
return err
}
}
switch method {
case "POST", "PUT":
if req.Header.Get("Content-Type") == "" {
req.Header.Set("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
}
}
if res, err = self.do(req); err != nil {
return err
}
if err = self.handleResponse(dst, res); err != nil {
return err
}
return nil
}
// Put performs a HTTP PUT request and, when complete, attempts to convert the
// response body into the datatype given by dst (a pointer to a struct, map or
// []byte array).
func (self *Client) Put(dst interface{}, path string, data url.Values) error {
var addr *url.URL
var err error
var body *strings.Reader
if addr, err = url.Parse(self.Prefix + strings.TrimLeft(path, "/")); err != nil {
return err
}
if data != nil {
body = strings.NewReader(data.Encode())
}
return self.newRequest(dst, "PUT", addr, body)
}
// Delete performs a HTTP DELETE request and, when complete, attempts to
// convert the response body into the datatype given by dst (a pointer to a
// struct, map or []byte array).
func (self *Client) Delete(dst interface{}, path string, data url.Values) error {
var addr *url.URL
var err error
var body *strings.Reader
if addr, err = url.Parse(self.Prefix + strings.TrimLeft(path, "/")); err != nil {
return err
}
if data != nil {
body = strings.NewReader(data.Encode())
}
return self.newRequest(dst, "DELETE", addr, body)
}
// PutMultipart performs a HTTP PUT multipart request and, when complete,
// attempts to convert the response body into the datatype given by dst (a
// pointer to a struct, map or []byte array).
func (self *Client) PutMultipart(dst interface{}, uri string, data *MultipartMessage) error {
var addr *url.URL
var err error
if addr, err = url.Parse(self.Prefix + strings.TrimLeft(uri, "/")); err != nil {
return err
}
return self.newMultipartRequest(dst, "PUT", addr, data)
}
// PostMultipart performs a HTTP POST multipart request and, when complete,
// attempts to convert the response body into the datatype given by dst (a
// pointer to a struct, map or []byte array).
func (self *Client) PostMultipart(dst interface{}, uri string, data *MultipartMessage) error {
var addr *url.URL
var err error
if addr, err = url.Parse(self.Prefix + strings.TrimLeft(uri, "/")); err != nil {
return err
}
return self.newMultipartRequest(dst, "POST", addr, data)
}
// PutRaw performs a HTTP PUT request with a custom body and, when complete,
// attempts to convert the response body into the datatype given by dst (a
// pointer to a struct, map or []byte array).
func (self *Client) PutRaw(dst interface{}, path string, body []byte) error {
var addr *url.URL
var err error
var bodyReader *strings.Reader
if addr, err = url.Parse(self.Prefix + strings.TrimLeft(path, "/")); err != nil {
return err
}
if body != nil {
bodyReader = strings.NewReader(string(body))
}
return self.newRequest(dst, "PUT", addr, bodyReader)
}
// PostRaw performs a HTTP POST request with a custom body and, when complete,
// attempts to convert the response body into the datatype given by dst (a
// pointer to a struct, map or []byte array).
func (self *Client) PostRaw(dst interface{}, path string, body []byte) error {
var addr *url.URL
var err error
var bodyReader *strings.Reader
if addr, err = url.Parse(self.Prefix + strings.TrimLeft(path, "/")); err != nil {
return err
}
if body != nil {
bodyReader = strings.NewReader(string(body))
}
return self.newRequest(dst, "POST", addr, bodyReader)
}
// Post performs a HTTP POST request and, when complete, attempts to convert
// the response body into the datatype given by dst (a pointer to a struct, map
// or []byte array).
func (self *Client) Post(dst interface{}, path string, data url.Values) error {
var addr *url.URL
var err error
var body *strings.Reader
if addr, err = url.Parse(self.Prefix + strings.TrimLeft(path, "/")); err != nil {
return err
}
if data != nil {
body = strings.NewReader(data.Encode())
}
return self.newRequest(dst, "POST", addr, body)
}
// Get performs a HTTP GET request and, when complete, attempts to convert the
// response body into the datatype given by dst (a pointer to a struct, map or
// []byte array).
func (self *Client) Get(dst interface{}, path string, data url.Values) error {
var addr *url.URL
var err error
if addr, err = url.Parse(self.Prefix + strings.TrimLeft(path, "/")); err != nil {
return err
}
if data != nil {
if addr.RawQuery == "" {
addr.RawQuery = data.Encode()
} else {
addr.RawQuery = addr.RawQuery + "&" + data.Encode()
}
}
return self.newRequest(dst, "GET", addr, nil)
}
// NewMultipartMessage creates a *MultipartMessage based on the given parameters.
// This is useful for PostMultipart() and PutMultipart().
func NewMultipartMessage(params url.Values, filemap FileMap) (*MultipartMessage, error) {
dst := bytes.NewBuffer(nil)
body := multipart.NewWriter(dst)
if filemap != nil {
for key, files := range filemap {
for _, file := range files {
writer, err := body.CreateFormFile(key, path.Base(file.Name))
if err != nil {
return nil, err
}
if _, err = io.Copy(writer, file.Reader); err != nil {
return nil, err
}
}
}
}
if params != nil {
for key := range params {
for _, value := range params[key] {
body.WriteField(key, value)
}
}
}
body.Close()
return &MultipartMessage{body.FormDataContentType(), dst}, nil
}
// Returns the body of the request as a io.ReadCloser
func (self *Client) body(res *http.Response) (io.ReadCloser, error) {
var body io.ReadCloser
var err error
if res.Header.Get("Content-Encoding") == "gzip" {
if body, err = gzip.NewReader(res.Body); err != nil {
return nil, err
}
} else {
body = res.Body
}
return body, nil
}
func fromBytes(dst reflect.Value, buf []byte) error {
var err error
switch dst.Kind() {
case reflect.String:
// string
dst.Set(reflect.ValueOf(string(buf)))
return nil
case reflect.Slice:
switch dst.Type().Elem().Kind() {
// []byte
case reflect.Uint8:
dst.Set(reflect.ValueOf(buf))
return nil
// []interface{}
case reflect.Interface:
t := []interface{}{}
err = json.Unmarshal(buf, &t)
if err == nil {
dst.Set(reflect.ValueOf(t))
return nil
}
}
case reflect.Map:
switch dst.Type().Elem().Kind() {
case reflect.Interface:
// map[string] interface{}
m := map[string]interface{}{}
err = json.Unmarshal(buf, &m)
if err == nil {
dst.Set(reflect.ValueOf(m))
return nil
}
}
}
if err != nil {
return err
}
return fmt.Errorf(ErrCouldNotConvert.Error(), reflect.TypeOf(buf), dst.Type())
}
func (self *Client) handleResponse(dst interface{}, res *http.Response) error {
body, err := self.body(res)
if err != nil {
return err
}
if dst == nil {
return nil
}
rv := reflect.ValueOf(dst)
if rv.Kind() != reflect.Ptr || rv.IsNil() {
return ErrDestinationNotAPointer
}
t := res.Header.Get("Content-Type")
switch rv.Elem().Type() {
case restResponseType:
var err error
r := Response{}
r.Body, err = ioutil.ReadAll(body)
if debugLevelEnabled(debugLevelVerbose) {
log.Printf("Body:\n%s\n", string(r.Body))
}
if err != nil {
return err
}
r.Header = res.Header
r.Status = res.Status
r.StatusCode = res.StatusCode
r.Proto = res.Proto
r.ProtoMajor = res.ProtoMajor
r.ProtoMinor = res.ProtoMinor
r.ContentLength = res.ContentLength
rv.Elem().Set(reflect.ValueOf(r))
case ioReadCloserType:
rv.Elem().Set(reflect.ValueOf(body))
case bytesBufferType:
buf, err := ioutil.ReadAll(body)
if debugLevelEnabled(debugLevelVerbose) {
log.Printf("Body:\n%s\n", string(buf))
}
if err != nil {
return err
}
dst := bytes.NewBuffer(buf)
rv.Elem().Set(reflect.ValueOf(dst))
default:
buf, err := ioutil.ReadAll(body)
if debugLevelEnabled(debugLevelVerbose) {
log.Printf("Body:\n%s\n", string(buf))
}
if err != nil {
return err
}
if strings.HasPrefix(t, "application/json") == true {
if rv.Elem().Kind() == reflect.Struct || rv.Elem().Kind() == reflect.Map {
err = json.Unmarshal(buf, dst)
return err
}
}
err = fromBytes(rv.Elem(), buf)
if err != nil {
return err
}
}
return nil
}
func (self *Client) do(req *http.Request) (*http.Response, error) {
var client http.Client
if self.TlsTransport != nil {
client = http.Client{
Transport: self.TlsTransport,
}
} else {
client = http.Client{}
}
// Adding cookie jar
if self.CookieJar != nil {
client.Jar = self.CookieJar
}
// Copying headers
for k := range self.Header {
req.Header.Set(k, self.Header.Get(k))
}
if req.Body == nil {
req.Header.Del("Content-Type")
req.Header.Del("Content-Length")
}
res, err := client.Do(req)
if debugLevelEnabled(debugLevelVerbose) {
log.Printf("Fetching %v\n", req.URL.String())
log.Printf("> %s %s", req.Method, req.Proto)
for k := range req.Header {
for kk := range req.Header[k] {
log.Printf("> %s: %s", k, req.Header[k][kk])
}
}
log.Printf("< %s %s", res.Proto, res.Status)
for k := range res.Header {
for kk := range res.Header[k] {
log.Printf("< %s: %s", k, res.Header[k][kk])
}
}
log.Printf("\n")
}
return res, err
}
// Get performs a HTTP GET request using the default client and, when complete,
// attempts to convert the response body into the datatype given by dst (a
// pointer to a struct, map or []byte array).
func Get(dest interface{}, uri string, data url.Values) error {
return DefaultClient.Get(dest, uri, data)
}
// Post performs a HTTP POST request using the default client and, when
// complete, attempts to convert the response body into the datatype given by
// dst (a pointer to a struct, map or []byte array).
func Post(dest interface{}, uri string, data url.Values) error {
return DefaultClient.Post(dest, uri, data)
}
// Put performs a HTTP PUT request using the default client and, when complete,
// attempts to convert the response body into the datatype given by dst (a
// pointer to a struct, map or []byte array).
func Put(dest interface{}, uri string, data url.Values) error {
return DefaultClient.Put(dest, uri, data)
}
// Delete performs a HTTP DELETE request using the default client and, when
// complete, attempts to convert the response body into the datatype given by
// dst (a pointer to a struct, map or []byte array).
func Delete(dest interface{}, uri string, data url.Values) error {
return DefaultClient.Delete(dest, uri, data)
}
// PostMultipart performs a HTTP POST multipart request using the default
// client and, when complete, attempts to convert the response body into the
// datatype given by dst (a pointer to a struct, map or []byte array).
func PostMultipart(dest interface{}, uri string, data *MultipartMessage) error {
return DefaultClient.PostMultipart(dest, uri, data)
}
// PutMultipart performs a HTTP PUT multipart request using the default client
// and, when complete, attempts to convert the response body into the datatype
// given by dst (a pointer to a struct, map or []byte array).
func PutMultipart(dest interface{}, uri string, data *MultipartMessage) error {
return DefaultClient.PutMultipart(dest, uri, data)
}