-
Notifications
You must be signed in to change notification settings - Fork 10
/
client.go
165 lines (132 loc) · 3.5 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
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
package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"net/http"
"time"
"github.com/geckoboard/sql-dataset/models"
)
type Client struct {
apiKey string
client *http.Client
}
type Error struct {
Detail `json:"error"`
}
type Detail struct {
Message string `json:"message"`
}
type DataPayload struct {
Data models.DatasetRows `json:"data"`
}
var (
gbHost = "https://api.geckoboard.com"
userAgent = fmt.Sprintf("SQL-Dataset/%s-%s", version, gitSHA)
maxRows = 500
errInvalidPayload = "There was an error sending the data to Geckoboard's API: %s"
errUnexpectedResponse = errors.New("Sorry, there seems to be a problem with " +
"Geckoboard's servers. Please try again, or check" +
"https://geckoboard.statuspage.io")
errMoreRowsToSend = "You're trying to send %d records, but 'replace' " +
"mode only supports sending %d. To send more, please change " +
"your dataset's update_type to 'append'\n"
)
func NewClient(apiKey string) *Client {
return &Client{
apiKey: apiKey,
client: &http.Client{Timeout: time.Second * 10},
}
}
func (c *Client) FindOrCreateDataset(ds *models.Dataset) error {
if err := ds.BuildSchemaFields(); err != nil {
return err
}
resp, err := c.makeRequest(http.MethodPut, fmt.Sprintf("/datasets/%s", ds.Name), ds)
if err != nil {
return err
}
defer resp.Body.Close()
return handleResponse(resp)
}
func (c *Client) DeleteDataset(name string) (err error) {
resp, err := c.makeRequest(http.MethodDelete, fmt.Sprintf("/datasets/%s", name), nil)
if err != nil {
return err
}
defer resp.Body.Close()
return handleResponse(resp)
}
func (c *Client) sendData(ds *models.Dataset, data models.DatasetRows) (err error) {
method := http.MethodPost
if ds.UpdateType == models.Replace {
method = http.MethodPut
}
resp, err := c.makeRequest(method, fmt.Sprintf("/datasets/%s/data", ds.Name), DataPayload{data})
if err != nil {
return err
}
defer resp.Body.Close()
return handleResponse(resp)
}
// SendAllData determines how to send the data to Geckoboard and returns an error
// if there is too much data for replace dataset and batches requests for append
func (c *Client) SendAllData(ds *models.Dataset, data models.DatasetRows) (err error) {
switch ds.UpdateType {
case models.Replace:
if len(data) > maxRows {
err = c.sendData(ds, data[0:maxRows])
if err == nil {
err = fmt.Errorf(errMoreRowsToSend, len(data), maxRows)
}
} else {
err = c.sendData(ds, data)
}
case models.Append:
grps := len(data) / maxRows
for i := 0; i <= grps; i++ {
batch := maxRows * i
if i == grps {
if batch+1 <= len(data) {
err = c.sendData(ds, data[batch:])
}
} else {
err = c.sendData(ds, data[batch:maxRows*(i+1)])
}
if err != nil {
return err
}
}
}
return err
}
func (c *Client) makeRequest(method, path string, body interface{}) (resp *http.Response, err error) {
var buf bytes.Buffer
if body != nil {
if err := json.NewEncoder(&buf).Encode(body); err != nil {
return nil, err
}
}
url := gbHost + path
req, err := http.NewRequest(method, url, &buf)
if err != nil {
return nil, err
}
req.Header.Set("User-Agent", userAgent)
req.SetBasicAuth(c.apiKey, "")
return c.client.Do(req)
}
func handleResponse(resp *http.Response) error {
res := resp.StatusCode
switch {
case res >= 200 && res < 300:
return nil
case res >= 400 && res < 500:
var err Error
json.NewDecoder(resp.Body).Decode(&err)
return fmt.Errorf(errInvalidPayload, err.Detail.Message)
default:
return errUnexpectedResponse
}
}