-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
80 lines (74 loc) · 1.97 KB
/
util.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
package gotau
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"time"
)
// Time wraps the standard time.Time to allow for custom parsing from json
type Time struct {
time.Time
}
// UnmarshalJSON implemented to allow for parsing this time object from TAU
func (t *Time) UnmarshalJSON(b []byte) error {
primaryLayout := "2006-01-02T15:04:05.999999999-07:00"
secondaryLayout := "2006-01-02T15:04:05.999999999-0700"
var timeAsString string
err := json.Unmarshal(b, &timeAsString)
timestamp, err := time.Parse(primaryLayout, timeAsString)
if err != nil {
timestamp, err = time.Parse(secondaryLayout, timeAsString)
if err != nil {
return err
}
}
t.Time = timestamp
return nil
}
func (c *Client) apiRequest(endpoint string, params map[string][]string, body []byte, method string) ([]byte, error) {
protocol := "http"
if c.hasSSL {
protocol = "https"
}
endpointURL := fmt.Sprintf("%s://%s:%d/api/v1/%s/", protocol, c.hostname, c.port, endpoint)
httpClient := &http.Client{}
buffer := bytes.NewBuffer(body)
request, err := http.NewRequest(method, endpointURL, buffer)
if err != nil {
return nil, err
}
request.Header.Add("Authorization", fmt.Sprintf("Token %s", c.token))
request.Header.Add("Content-Type", "application/json")
_, err = request.URL.Parse(endpointURL)
if err != nil {
return nil, err
}
q := request.URL.Query()
q.Add("format", "json")
for key, values := range params {
for _, item := range values {
q.Add(key, item)
}
}
request.URL.RawQuery = q.Encode()
response, err := httpClient.Do(request)
if err != nil {
return nil, err
}
if response.StatusCode >= 200 && response.StatusCode < 300 {
body, err := ioutil.ReadAll(response.Body)
return body, err
}
if response.StatusCode == 401 {
return nil, AuthorizationError{}
}
body, _ = ioutil.ReadAll(response.Body)
err = GenericError{
Err: fmt.Sprintf("response Code %d: %s", response.StatusCode, body),
Body: body,
Code: response.StatusCode,
}
return nil, err
}