forked from nukosuke/go-zendesk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
zendesk.go
256 lines (213 loc) · 5.42 KB
/
zendesk.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
package zendesk
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"regexp"
"strings"
)
const (
baseURLFormat = "https://%s.zendesk.com/api/v2"
headerRateLimit = "X-RateLimit-Limit"
headerRateRemaining = "X-RateLimit-Remaining"
)
var defaultHeaders = map[string]string{
"User-Agent": "nukosuke/go-zendesk",
"Content-Type": "application/json",
}
// Error an error type containing the http response from zendesk
type Error struct {
body []byte
resp *http.Response
}
// Error the error string for this error
func (e Error) Error() string {
msg := string(e.body)
if msg == "" {
msg = http.StatusText(e.Status())
}
return fmt.Sprintf("%d: %s", e.resp.StatusCode, msg)
}
// Body is the Body of the HTTP response
func (e Error) Body() io.ReadCloser {
return ioutil.NopCloser(bytes.NewBuffer(e.body))
}
// Headers the HTTP headers returned from zendesk
func (e Error) Headers() http.Header {
return e.resp.Header
}
// Status the HTTP status code returned from zendesk
func (e Error) Status() int {
return e.resp.StatusCode
}
var subdomainRegexp = regexp.MustCompile("^[a-z][a-z0-9-]+[a-z0-9]$")
// Client of Zendesk API
type Client struct {
baseURL *url.URL
httpClient *http.Client
credential Credential
headers map[string]string
}
// NewClient creates new Zendesk API client
func NewClient(httpClient *http.Client) (*Client, error) {
if httpClient == nil {
httpClient = http.DefaultClient
}
client := &Client{httpClient: httpClient}
client.headers = defaultHeaders
return client, nil
}
// SetHeader saves HTTP header in client. It will be included all API request
func (z *Client) SetHeader(key string, value string) {
z.headers[key] = value
}
// SetSubdomain saves subdomain in client. It will be used
// when call API
func (z *Client) SetSubdomain(subdomain string) error {
if !subdomainRegexp.MatchString(subdomain) {
return fmt.Errorf("%s is invalid subdomain", subdomain)
}
baseURLString := fmt.Sprintf(baseURLFormat, subdomain)
baseURL, err := url.Parse(baseURLString)
if err != nil {
return err
}
z.baseURL = baseURL
return nil
}
// SetEndpointURL replace full URL of endpoint without subdomain validation.
// This is mainly used for testing to point to mock API server.
func (z *Client) SetEndpointURL(newURL string) error {
baseURL, err := url.Parse(newURL)
if err != nil {
return err
}
z.baseURL = baseURL
return nil
}
// SetCredential saves credential in client. It will be set
// to request header when call API
func (z *Client) SetCredential(cred Credential) {
z.credential = cred
}
// Get get JSON data from API and returns its body as []bytes
func (z Client) Get(path string) ([]byte, error) {
req, err := http.NewRequest("GET", z.baseURL.String()+path, nil)
if err != nil {
return nil, err
}
z.includeHeaders(req)
req.SetBasicAuth(z.credential.Email(), z.credential.Secret())
resp, err := z.httpClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
return nil, Error{
body: body,
resp: resp,
}
}
return body, nil
}
// Post send data to API and returns response body as []bytes
func (z Client) Post(path string, data interface{}) ([]byte, error) {
bytes, err := json.Marshal(data)
if err != nil {
return nil, err
}
req, err := http.NewRequest("POST", z.baseURL.String()+path, strings.NewReader(string(bytes)))
if err != nil {
return nil, err
}
z.includeHeaders(req)
req.SetBasicAuth(z.credential.Email(), z.credential.Secret())
resp, err := z.httpClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusCreated {
return nil, Error{
body: body,
resp: resp,
}
}
return body, nil
}
// Put sends data to API and returns response body as []bytes
func (z Client) Put(path string, data interface{}) ([]byte, error) {
bytes, err := json.Marshal(data)
if err != nil {
return nil, err
}
req, err := http.NewRequest(http.MethodPut, z.baseURL.String()+path, strings.NewReader(string(bytes)))
if err != nil {
return nil, err
}
z.prepareRequest(req)
resp, err := z.httpClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
return nil, Error{
body: body,
resp: resp,
}
}
return body, nil
}
// Delete sends data to API and returns an error if unsuccessful
func (z Client) Delete(path string) error {
req, err := http.NewRequest(http.MethodDelete, z.baseURL.String()+path, nil)
if err != nil {
return err
}
z.prepareRequest(req)
resp, err := z.httpClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
if resp.StatusCode != http.StatusNoContent {
return Error{
body: body,
resp: resp,
}
}
return nil
}
// prepare request sets common request variables such as authn and user agent
func (z *Client) prepareRequest(req *http.Request) {
z.includeHeaders(req)
req.SetBasicAuth(z.credential.Email(), z.credential.Secret())
}
// includeHeaders set HTTP headers from client.headers to *http.Request
func (z *Client) includeHeaders(req *http.Request) {
for key, value := range z.headers {
req.Header.Set(key, value)
}
}