forked from customerio/go-customerio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.go
69 lines (57 loc) · 1.43 KB
/
api.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
package customerio
import (
"bytes"
"context"
"encoding/json"
"io"
"io/ioutil"
"net/http"
)
type APIClient struct {
Key string
URL string
UserAgent string
Client *http.Client
}
// NewAPIClient prepares a client for use with the Customer.io API, see: https://customer.io/docs/api/#apicoreintroduction
// using an App API Key from https://fly.customer.io/settings/api_credentials?keyType=app
func NewAPIClient(key string, opts ...option) *APIClient {
client := &APIClient{
Key: key,
Client: http.DefaultClient,
URL: "https://api.customer.io",
UserAgent: DefaultUserAgent,
}
for _, opt := range opts {
opt.api(client)
}
return client
}
func (c *APIClient) doRequest(ctx context.Context, verb, requestPath string, body interface{}) ([]byte, int, error) {
var payload io.Reader
if body != nil {
b, err := json.Marshal(body)
if err != nil {
return nil, 0, err
}
payload = bytes.NewBuffer(b)
}
req, err := http.NewRequest(verb, c.URL+requestPath, payload)
if err != nil {
return nil, 0, err
}
req = req.WithContext(ctx)
req.Header.Set("Authorization", "Bearer "+c.Key)
req.Header.Set("Content-Type", "application/json")
req.Header.Add("User-Agent", c.UserAgent)
resp, err := c.Client.Do(req)
if err != nil {
return nil, 0, err
}
defer resp.Body.Close()
respBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, 0, err
}
return respBody, resp.StatusCode, nil
}