-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.go
78 lines (72 loc) · 1.59 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
package gorte
import (
"encoding/json"
"io"
"net/http"
"net/url"
"github.com/google/go-querystring/query"
"github.com/hashicorp/go-retryablehttp"
)
func URLGenerator(ur *url.URL, path string) (*url.URL, error) {
u := *ur
unescaped, err := url.PathUnescape(path)
if err != nil {
return nil, err
}
// Set the encoded path data
u.RawPath = u.Path + path
u.Path = u.Path + unescaped
return &u, nil
}
func (c *Client) NewRequest(method, path string, opt interface{}) (*retryablehttp.Request, error) {
u, err := URLGenerator(c.baseURL, path)
if err != nil {
return nil, err
}
reqHeaders := make(http.Header)
reqHeaders.Set("Accept", "application/json")
var body interface{}
switch {
case method == http.MethodPost || method == http.MethodPut:
reqHeaders.Set("Content-Type", "application/json")
if opt != nil {
body, err = json.Marshal(opt)
if err != nil {
return nil, err
}
}
case opt != nil:
q, err := query.Values(opt)
if err != nil {
return nil, err
}
u.RawQuery = q.Encode()
}
req, err := retryablehttp.NewRequest(method, u.String(), body)
if err != nil {
return nil, err
}
for k, v := range reqHeaders {
req.Header[k] = v
}
err = c.authenticate(req)
if err != nil {
return nil, err
}
return req, nil
}
func (c *Client) Do(req *retryablehttp.Request, v interface{}) (*http.Response, error) {
resp, err := c.client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if v != nil {
if w, ok := v.(io.Writer); ok {
_, err = io.Copy(w, resp.Body)
} else {
err = json.NewDecoder(resp.Body).Decode(v)
}
}
return resp, err
}