forked from RichardKnop/go-mailchimp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
81 lines (71 loc) · 1.75 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
package mailchimp
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strings"
)
// 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) (ClientInterface, 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] // data center
if httpClient == nil {
httpClient = http.DefaultClient
}
baseURL, err := url.Parse(fmt.Sprintf("https://%s.api.mailchimp.com/3.0", dc))
if err != nil {
return nil, err
}
return &Client{
client: httpClient,
baseURL: baseURL,
apiKey: apiKey,
dc: dc,
}, nil
}
// GetBaseURL ...
func (c *Client) GetBaseURL() *url.URL {
return c.baseURL
}
// SetBaseURL ...
func (c *Client) SetBaseURL(baseURL *url.URL) {
c.baseURL = baseURL
}
func (c *Client) do(method string, path string, body interface{}) (*http.Response, 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.GetBaseURL(), path)
req, err := http.NewRequest(method, apiURL, buf)
if err != nil {
return nil, err
}
req.SetBasicAuth("", c.apiKey)
return c.client.Do(req)
}
func extractError(data []byte) (*ErrorResponse, error) {
errorResponse := new(ErrorResponse)
if err := json.Unmarshal(data, errorResponse); err != nil {
return nil, err
}
return errorResponse, nil
}