-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathalvtimeClient.go
98 lines (81 loc) · 1.78 KB
/
alvtimeClient.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
package alvtimeclient
import (
"bytes"
"encoding/json"
"errors"
"io/ioutil"
"net/http"
"net/url"
"strconv"
)
// AlvtimeClient client struct
type AlvtimeClient struct {
domain string
accessToken string
httpClient
}
type httpClient interface {
Do(req *http.Request) (*http.Response, error)
}
type requestError struct {
Code string `json:"code"`
Error string `json:"error"`
}
// New is a helper function to create a *AlvtimeClient based on a domain string
func New(domain, accessToken string) (*AlvtimeClient, error) {
c := &AlvtimeClient{
domain: domain,
accessToken: accessToken,
httpClient: &http.Client{},
}
return c, nil
}
func (c *AlvtimeClient) newRequest(
method string,
baseURL *url.URL,
body interface{},
) (
*http.Request,
error,
) {
uri := baseURL.String()
bytesBuffer, err := createBytesBuffer(body)
if err != nil {
return nil, err
}
req, err := http.NewRequest(method, uri, bytesBuffer)
if err != nil {
return nil, err
}
req.Header.Add("Authorization", "Bearer "+c.accessToken)
return req, nil
}
func (c *AlvtimeClient) do(req *http.Request) ([]byte, error) {
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, err
}
var byteArr []byte
byteArr, err = ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
resp.Body.Close()
if resp.StatusCode != http.StatusOK {
var e requestError
json.Unmarshal(byteArr, &e)
err = errors.New(
"\n\tRequest StatusCode: " + strconv.Itoa(resp.StatusCode) +
", \n\tStatus: " + resp.Status,
)
return nil, err
}
return byteArr, nil
}
func createBytesBuffer(payload interface{}) (*bytes.Buffer, error) {
b, err := json.Marshal(payload)
if err != nil {
return nil, err
}
return bytes.NewBuffer(b), nil
}