-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontacts.go
105 lines (79 loc) · 1.99 KB
/
contacts.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
package contacts
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
)
const sendgridAPIv3Base = "https://api.sendgrid.com/v3"
func New(apikey string) *Client {
if apikey == "" {
panic(errors.New("contacts: apikey must be set"))
}
return &Client{
APIKey: apikey,
HTTPClient: http.DefaultClient,
}
}
type Client struct {
APIKey string
HTTPClient *http.Client
}
func (c *Client) makeRequest(method, url string, data, output interface{}) error {
var body io.Reader
if method != http.MethodGet && data != nil {
var err error
body, err = c.marshal(data)
if err != nil {
return err
}
}
req, err := http.NewRequest(method, sendgridAPIv3Base+url, body)
if err != nil {
return err
}
req.Header.Add("Authorization", "Bearer "+c.APIKey)
req.Header.Add("Content-Type", "application/json")
resp, err := c.HTTPClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if output != nil && resp.StatusCode < http.StatusBadRequest {
err = c.unmarshal(resp.Body, output)
return err
} else if resp.StatusCode >= http.StatusBadRequest {
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("contacts: bad status code observed: %d", resp.StatusCode)
} else {
return fmt.Errorf("contacts: bad status code observed: %d, body: %s", resp.StatusCode, string(b))
}
}
return nil
}
func (c *Client) marshal(data interface{}) (io.Reader, error) {
buf := new(bytes.Buffer)
if err := json.NewEncoder(buf).Encode(data); err != nil {
return nil, err
}
return buf, nil
}
func (c *Client) unmarshal(r io.Reader, into interface{}) error {
return json.NewDecoder(r).Decode(into)
}
func (c *Client) Recipients() *RecipientClient {
return &RecipientClient{client: c}
}
func (c *Client) Lists() *ListsClient {
return &ListsClient{client: c}
}
func (c *Client) Segments() *SegmentsClient {
return &SegmentsClient{client: c}
}
func (c *Client) CustomFields() *CustomFieldsClient {
return &CustomFieldsClient{client: c}
}