This repository has been archived by the owner on Jan 12, 2024. It is now read-only.
forked from mnbbrown/mailchimp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mailchimp.go
103 lines (90 loc) · 2.36 KB
/
mailchimp.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
package mailchimp
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"strings"
)
// A Client manages communication with the Mailchimp API.
type Client struct {
client *http.Client
BaseURL *url.URL
DC string
APIKey string
}
// NewClient returns a new Mailchimp API client. If a nil httpClient is
// provided, http.DefaultClient will be used. The apiKey must be in the format xyz-us11.
func NewClient(apiKey string, httpClient *http.Client) (*Client, error) {
if len(strings.Split(apiKey, "-")) != 2 {
return nil, errors.New("Mailchimp API Key must be formatted like: xyz-zys")
}
dc := strings.Split(apiKey, "-")[1]
if httpClient == nil {
httpClient = http.DefaultClient
}
baseUrl, _ := url.Parse(fmt.Sprintf("https://%s.api.mailchimp.com/3.0", dc))
return &Client{APIKey: apiKey, client: httpClient, DC: dc, BaseURL: baseUrl}, nil
}
type ErrorResponse struct {
Type string `json:type"`
Title string `json:"title"`
Status int `json:"status"`
Detail string `json:"detail"`
}
func (e ErrorResponse) Error() string {
return fmt.Sprintf("Error %d %s (%s)", e.Status, e.Title, e.Detail)
}
func CheckResponse(r *http.Response) error {
if c := r.StatusCode; 200 <= c && c <= 299 {
return nil
}
errorResponse := &ErrorResponse{}
data, err := ioutil.ReadAll(r.Body)
if err == nil && data != nil {
json.Unmarshal(data, errorResponse)
}
return errorResponse
}
func (c *Client) Do(method string, path string, body interface{}) (interface{}, error) {
var buf io.ReadWriter
if body != nil {
buf = new(bytes.Buffer)
err := json.NewEncoder(buf).Encode(body)
if err != nil {
return nil, err
}
}
apiURL := fmt.Sprintf("%s%s", c.BaseURL.String(), path)
req, err := http.NewRequest(method, apiURL, buf)
if err != nil {
return nil, err
}
req.SetBasicAuth("", c.APIKey)
resp, err := c.client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
err = CheckResponse(resp)
if err != nil {
return nil, err
}
var v interface{}
err = json.NewDecoder(resp.Body).Decode(&v)
if err != nil {
return nil, err
}
return v, nil
}
func (c *Client) Subscribe(email string, listId string) (interface{}, error) {
v, err := c.Do("POST", fmt.Sprintf("/lists/%s/members/", listId), &map[string]string{"email_address": email, "status": "subscribed"})
if err != nil {
return v, err
}
return v, nil
}