-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
89 lines (70 loc) · 1.63 KB
/
client.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
package geckoboard
import (
"encoding/json"
"errors"
"io"
"net/http"
"time"
)
var (
errUnexpectedResponse = errors.New("Sorry, there seems to be a problem with " +
"Geckoboard's servers. Please try again, or check" +
"https://geckoboard.statuspage.io")
)
type Client struct {
client *http.Client
baseURL string
apiKey string
}
func New(apikey string) *Client {
return NewWithURL(apikey, "https://api.geckoboard.com")
}
func NewWithURL(apikey, baseURL string) *Client {
return &Client{
client: &http.Client{Timeout: 30 * time.Second},
baseURL: baseURL,
apiKey: apikey,
}
}
func (c *Client) DatasetService() DatasetService {
return &datasetService{
client: c,
maxRecordsPerReq: 500,
jsonMarshalFn: json.Marshal,
}
}
func (c *Client) buildRequest(method, path string, body io.Reader) (*http.Request, error) {
r, err := http.NewRequest(method, c.baseURL+path, body)
if err != nil {
return nil, err
}
r.SetBasicAuth(c.apiKey, "")
if body != nil {
r.Header.Add("Content-Type", "application/json")
}
return r, nil
}
func (c *Client) doRequest(req *http.Request) error {
resp, err := c.client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if err := c.checkResponse(resp); err != nil {
return err
}
return nil
}
func (c *Client) checkResponse(resp *http.Response) error {
if resp.StatusCode < http.StatusMultipleChoices {
return nil
}
if resp.StatusCode >= http.StatusInternalServerError {
return errUnexpectedResponse
}
gerr := &Error{StatusCode: resp.StatusCode}
if err := json.NewDecoder(resp.Body).Decode(&gerr); err != nil {
return err
}
return gerr
}