-
Notifications
You must be signed in to change notification settings - Fork 4
/
client_requests.go
120 lines (92 loc) · 2.51 KB
/
client_requests.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
package gomo
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
)
// Post makes a POST request to the API
func (c *Client) Post(endpoint string, resource interface{}) (wrapper, error) {
wrapper := newWrapper("post", endpoint, resource)
return wrapper, c.do(&wrapper)
}
// Get makes a GET request to the API
func (c *Client) Get(endpoint string, resource ...interface{}) (wrapper, error) {
wrapper := newWrapper("get", endpoint, resource...)
return wrapper, c.do(&wrapper)
}
// Delete makes a DELETE request to the API
func (c *Client) Delete(endpoint string) (wrapper, error) {
wrapper := newWrapper("delete", endpoint)
return wrapper, c.do(&wrapper)
}
// Put makes a PUT request to the API
func (c *Client) Put(endpoint string, resource interface{}) (wrapper, error) {
wrapper := newWrapper("put", endpoint, resource)
return wrapper, c.do(&wrapper)
}
func (c Client) url(endpoint string) string {
return fmt.Sprintf("%s/%s/%s", c.Endpoint, c.APIVersion, endpoint)
}
func (c *Client) do(wrapper *wrapper) error {
var err error
resp, err := c.makeRequest(wrapper)
if err != nil {
return err
}
return c.parseResponse(resp, wrapper)
}
func (c Client) buildRequest(method string, endpoint string, body []byte) (*http.Request, error) {
var err error
req, err := http.NewRequest(method, c.url(endpoint), bytes.NewBuffer(body))
if err != nil {
return nil, err
}
req.Header.Add("Authorization", fmt.Sprintf("Bearer: %s", c.AccessToken))
req.Header.Add("Content-Type", "application/json")
req.Header.Add("User-Agent", defaultUserAgent)
return req, nil
}
func (c *Client) makeRequest(wrapper *wrapper) (*http.Response, error) {
var body []byte
if wrapper.Body != nil {
rb := response{
Data: wrapper.Body,
}
rbj, err := json.Marshal(rb)
if err != nil {
return nil, err
}
body = rbj
}
req, err := c.buildRequest(wrapper.Method, wrapper.Endpoint, body)
wrapper.Request = req
if err != nil {
return nil, err
}
wrapper.ExecutionTime.Start()
resp, err := c.httpClient.Do(wrapper.Request)
wrapper.ExecutionTime.End()
if err != nil {
return nil, err
}
return resp, nil
}
func (c Client) parseResponse(resp *http.Response, wrapper *wrapper) error {
wrapper.StatusCode = resp.StatusCode
defer resp.Body.Close()
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
err = json.Unmarshal(b, &wrapper.Response)
if err != nil {
return err
}
if len(wrapper.Response.Errors) > 0 {
return errors.New(wrapper.Response.Errors[0].Detail)
}
return nil
}