-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathclient.go
264 lines (222 loc) · 6.96 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
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
257
258
259
260
261
262
263
264
package geckoclient
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strings"
"time"
)
var (
api = "https://api.geckoboard.com"
hclient = &http.Client{
Timeout: time.Second * 30,
}
)
// errors ...
var (
ErrRequestConflict = errors.New("request encountered resource conflict")
ErrInvalidRequest = errors.New("request failed: unknown status response")
ErrBadCredentials = errors.New("request denied due to bad auth crendentials")
ErrFailedRequest = errors.New("request is invalid: api respond as bad request")
ErrInvalidResponseType = errors.New("invalid response type, expected 'application/json'")
ErrExceededPushLimit = errors.New("api user has exceeded POST/PUSH limit, please wait a while")
)
// NewDataset embodies the data sent as json to create a new
// data set within user associated account.
type NewDataset struct {
Fields map[string]DataType
UniqueBy []string
}
// Dataset embodies the data send along a http request to either add, update or replace
// existing dataset data for a existing dataset within user's Geckoboard account.
type Dataset struct {
// Data to be added to or replace existing dataset data.
Data []map[string]interface{} `json:"data"`
// Provide field names of dataset to use as deletion criteria.
// Only used when adding or appending more data, not when replacing datasets
// data.
DeleteBy []string `json:"delete_by,omitempty"`
}
// APIError embodies the data received from the GeckoBoard API when
// a request returns an associated error response.
type APIError struct {
Err error
Message string
}
// Error returns associated error associated with the instance.
func (a APIError) Error() string {
if a.Message == "" {
return a.Err.Error()
}
return a.Message + " : " + a.Err.Error()
}
// Client embodies a http client for interacting with the GeckoBoard API.
type Client struct {
auth string
agent string
apiURL string
}
// New returns a new instance of a Client for interacting with
// the Geckoboard API.
func New(authKey string) (Client, error) {
return CustomClient(api, authKey, "")
}
// NewWithUserAgent returns a new instance of a Client for interacting with
// the Geckoboard API.
func NewWithUserAgent(authKey string, agent string) (Client, error) {
return CustomClient(api, authKey, agent)
}
// CustomClient returns a new instance of a Client for interacting with
// the Geckoboard API found from provided apiURL provided with auth key and agent
// name if provided.
func CustomClient(apiURL string, authKey string, agent string) (Client, error) {
var gc Client
gc.agent = agent
gc.auth = authKey
gc.apiURL = apiURL
return gc, gc.verify()
}
// ReplaceData replaces all data with provided set for giving datasetID if it exists within user's
// Geckoboard API account based on Auth key.
//
// PUT https://api.geckoboard.com/datasets/:datasetid/data
//
// Note: Dataset.DeleteBy is ignored and not used during this call.
func (gc Client) ReplaceData(ctx context.Context, datasetID string, data Dataset) error {
var body bytes.Buffer
if err := json.NewEncoder(&body).Encode(data); err != nil {
return err
}
res, err := gc.doRequest(ctx, "PUT", fmt.Sprintf("datasets/%s/data", datasetID), &body)
if err != nil {
return err
}
defer res.Close()
return nil
}
// PushData adds new data into the data set uploaded to the Geckoboard API represented by
// the provided ID. The data are added if new and will be merged based on standards of the
// unique_by field names if present within dataset.
//
// POST https://api.geckoboard.com/datasets/:datasetid/data
//
// NOTE: To replace use Client.ReplaceData.
// NOTE: Dataset.DeleteBy is used if provided, during this call.
func (gc Client) PushData(ctx context.Context, datasetID string, data Dataset) error {
var body bytes.Buffer
if err := json.NewEncoder(&body).Encode(data); err != nil {
return err
}
res, err := gc.doRequest(ctx, "POST", fmt.Sprintf("datasets/%s/data", datasetID), &body)
if err != nil {
return err
}
defer res.Close()
return nil
}
// Delete sends a request to delete dataset marked by provided datasetID. It issues a DELETE request
// to the Geckoboard API.
//
// DELETE https://api.geckoboard.com/datasets/:datasetid
//
func (gc Client) Delete(ctx context.Context, datasetID string) error {
res, err := gc.doRequest(ctx, "DELETE", fmt.Sprintf("datasets/%s", datasetID), nil)
if err != nil {
return err
}
defer res.Close()
return nil
}
// Create sends a request to create the provided dataset by issuing a http request
// to the Geckoboard API.
//
// PUT https://api.geckoboard.com/datasets/:datasetid
//
func (gc Client) Create(ctx context.Context, datasetID string, set NewDataset) error {
newData := struct {
Fields map[string]interface{} `json:"fields"`
UniqueBy []string `json:"unique_by,omitempty"`
}{
Fields: map[string]interface{}{},
}
newData.UniqueBy = set.UniqueBy
for name, field := range set.Fields {
newData.Fields[name] = field.Field()
}
var body bytes.Buffer
if err := json.NewEncoder(&body).Encode(newData); err != nil {
return err
}
res, err := gc.doRequest(ctx, "PUT", fmt.Sprintf("datasets/%s", datasetID), &body)
if err != nil {
return err
}
defer res.Close()
return nil
}
// verify validates authenticity of api token for giving client.
func (gc Client) verify() error {
_, err := gc.doRequest(context.Background(), "GET", "/", nil)
return err
}
// doRequest contains necessary logic to send request to API endpoint and appropriately return
// desired response.
func (gc Client) doRequest(ctx context.Context, method string, path string, body io.Reader) (io.ReadCloser, error) {
req, err := http.NewRequest(method, fmt.Sprintf("%s/%s", gc.apiURL, path), body)
if err != nil {
return nil, err
}
if ctx != nil {
req = req.WithContext(ctx)
}
req.SetBasicAuth(gc.auth, "")
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
if gc.agent != "" {
req.Header.Set("User-Agent", gc.agent)
}
res, err := hclient.Do(req)
if err != nil {
return nil, err
}
if res.StatusCode >= 200 && res.StatusCode < 300 {
return res.Body, nil
}
defer res.Body.Close()
var recErr = struct {
Error APIError `json:"error"`
}{}
if !strings.Contains(res.Header.Get("Content-Type"), "application/json") {
recErr.Error.Err = ErrInvalidResponseType
return nil, recErr.Error
}
if err := json.NewDecoder(res.Body).Decode(&recErr); err != nil {
recErr.Error.Err = err
return nil, recErr.Error
}
if res.StatusCode >= 400 {
if res.StatusCode == 429 {
recErr.Error.Err = ErrExceededPushLimit
return nil, recErr.Error
}
if res.StatusCode == http.StatusConflict {
recErr.Error.Err = ErrRequestConflict
return nil, recErr.Error
}
if res.StatusCode == http.StatusBadRequest {
recErr.Error.Err = ErrFailedRequest
return nil, recErr.Error
}
if res.StatusCode == http.StatusUnauthorized {
recErr.Error.Err = ErrBadCredentials
return nil, recErr.Error
}
}
recErr.Error.Err = ErrInvalidRequest
return nil, recErr.Error
}