-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
80 lines (65 loc) · 1.67 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
// Package iterate provides access to the Iterate API
package iterate
import (
"bytes"
"encoding/json"
"errors"
"io/ioutil"
"net/http"
"net/url"
)
const host = "https://iteratehq.com/api/v1"
// Client manages the communication with the Iterate API.
type Client struct {
host string
httpClient *http.Client
token string
version string
}
// NewClient creates a new client with an API auth token.
func New(token string) Client {
version := "20161109"
return Client{
host: host,
httpClient: &http.Client{},
token: token,
version: version,
}
}
func (c Client) get(path string, values url.Values) ([]byte, error) {
r, _ := http.NewRequest("GET", c.host+path, nil)
r.URL.RawQuery = c.withDefaultParams(values).Encode()
return c.sendRequest(r)
}
func (c Client) post(path string, values url.Values) ([]byte, error) {
// Configure the request
r, _ := http.NewRequest("POST", c.host+path, bytes.NewBufferString(c.withDefaultParams(values).Encode()))
r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
return c.sendRequest(r)
}
func (c Client) sendRequest(r *http.Request) (results []byte, err error) {
// Send the request
rawResp, err := c.httpClient.Do(r)
if err != nil {
return
}
defer rawResp.Body.Close()
body, err := ioutil.ReadAll(rawResp.Body)
// Parse the response
var resp Response
err = json.Unmarshal(body, &resp)
if err != nil {
return
}
if resp.Error != "" {
err = errors.New(resp.Error)
return
}
results, err = json.Marshal(resp.Results)
return
}
func (c Client) withDefaultParams(values url.Values) url.Values {
values.Add("v", c.version)
values.Add("access_token", c.token)
return values
}