forked from customerio/go-customerio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
273 lines (244 loc) · 7.64 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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
package customerio
import (
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"net/http"
"strconv"
"strings"
"time"
"github.com/go-resty/resty/v2"
)
// Client is the CustomerIO client/configuration
type Client struct {
httpClient *resty.Client
options *clientOptions // Options are all the default settings / configuration
}
// ClientOptions holds all the configuration for client requests and default resources
// See: https://fly.customer.io/settings/api_credentials
type clientOptions struct {
apiURL string // Regional API endpoint (URL)
appAPIKey string // App or Beta API key
betaURL string // Regional API endpoint (Beta URL)
httpTimeout time.Duration // Default timeout in seconds for GET requests
requestTracing bool // If enabled, it will trace the request timing
retryCount int // Default retry count for HTTP requests
siteID string // Used in conjunction with the Tracking API key
trackingAPIKey string // Tracking API key (Only tracking API requests)
trackURL string // Regional Tracking API endpoint (URL)
userAgent string // User agent for all outgoing requests
}
// region is used for changing the location of the API endpoints
type region struct {
apiURL string
betaURL string
trackURL string
}
// Current regions available
var (
RegionUS = region{
apiURL: "https://api.customer.io",
betaURL: "https://beta-api.customer.io",
trackURL: "https://track.customer.io",
}
RegionEU = region{
apiURL: "https://api-eu.customer.io",
betaURL: "https://beta-api.customer.io",
trackURL: "https://track-eu.customer.io",
}
)
// ClientOps allow functional options to be supplied
// that overwrite default client options.
type ClientOps func(c *clientOptions)
// WithRegion will change the region API endpoints
func WithRegion(r region) ClientOps {
return func(c *clientOptions) {
c.apiURL = r.apiURL
c.betaURL = r.betaURL
c.trackURL = r.trackURL
}
}
// WithHTTPTimeout can be supplied to adjust the default http client timeouts.
// The http client is used when creating requests
// Default timeout is 20 seconds.
func WithHTTPTimeout(timeout time.Duration) ClientOps {
return func(c *clientOptions) {
c.httpTimeout = timeout
}
}
// WithRequestTracing will enable tracing.
// Tracing is disabled by default.
func WithRequestTracing() ClientOps {
return func(c *clientOptions) {
c.requestTracing = true
}
}
// WithRetryCount will overwrite the default retry count for http requests.
// Default retries is 2.
func WithRetryCount(retries int) ClientOps {
return func(c *clientOptions) {
c.retryCount = retries
}
}
// WithUserAgent will overwrite the default useragent.
// Default is package name + version.
func WithUserAgent(userAgent string) ClientOps {
return func(c *clientOptions) {
c.userAgent = userAgent
}
}
// WithTrackingKey will provide the SiteID and Tracking API key
// See: https://fly.customer.io/settings/api_credentials
func WithTrackingKey(siteID, trackingAPIKey string) ClientOps {
return func(c *clientOptions) {
c.siteID = siteID
c.trackingAPIKey = trackingAPIKey
}
}
// WithAppKey will provide the App or Beta API key
// See: https://fly.customer.io/settings/api_credentials?keyType=app
func WithAppKey(appAPIKey string) ClientOps {
return func(c *clientOptions) {
c.appAPIKey = appAPIKey
}
}
// WithCustomHTTPClient will overwrite the default client with a custom client.
func (c *Client) WithCustomHTTPClient(client *resty.Client) *Client {
c.httpClient = client
return c
}
// GetUserAgent will return the user agent string of the client
func (c *Client) GetUserAgent() string {
return c.options.userAgent
}
// defaultClientOptions will return an Options struct with the default settings
//
// Useful for starting with the default and then modifying as needed
func defaultClientOptions() (opts *clientOptions) {
// Set the default options
opts = &clientOptions{
apiURL: RegionUS.apiURL,
betaURL: RegionUS.betaURL,
httpTimeout: defaultHTTPTimeout,
requestTracing: false,
retryCount: defaultRetryCount,
trackURL: RegionUS.trackURL,
userAgent: defaultUserAgent,
}
return
}
// NewClient creates a new client for all CustomerIO requests (tracking, app, beta)
//
// If no options are given, it will use the DefaultClientOptions()
// If no client is supplied it will use a default Resty HTTP client
func NewClient(opts ...ClientOps) (*Client, error) {
defaults := defaultClientOptions()
// Create a new client
client := &Client{
options: defaults,
}
// overwrite defaults with any set by user
for _, opt := range opts {
opt(client.options)
}
// Check for at least one type of API key
if client.options.trackingAPIKey == "" && client.options.appAPIKey == "" {
return nil, errors.New("missing an API Key (Tracking or App)")
}
// Set the Resty HTTP client
if client.httpClient == nil {
client.httpClient = resty.New()
// Set defaults (for GET requests)
client.httpClient.SetTimeout(client.options.httpTimeout)
client.httpClient.SetRetryCount(client.options.retryCount)
}
return client, nil
}
// auth creates the Basic Auth string using the SiteID and API Key
func (c *Client) auth() string {
return base64.URLEncoding.EncodeToString([]byte(fmt.Sprintf("%v:%v", c.options.siteID, c.options.trackingAPIKey)))
}
// request is a standard GET / POST / PUT / DELETE request for all outgoing HTTP requests
// Omit the data attribute if using a GET request
func (c *Client) request(httpMethod string, requestURL string,
data interface{}) (response StandardResponse, err error) {
// Set the user agent
req := c.httpClient.R().SetHeader("User-Agent", c.options.userAgent)
// Set the body if (PUT || POST)
if httpMethod != http.MethodGet && httpMethod != http.MethodDelete {
var j []byte
if j, err = json.Marshal(data); err != nil {
return
}
req = req.SetBody(string(j))
req.Header.Add("Content-Length", strconv.Itoa(len(j)))
req.Header.Set("Content-Type", "application/json")
}
// Enable tracing
if c.options.requestTracing {
req.EnableTrace()
}
// Set the authorization and content type
if strings.Contains(requestURL, c.options.trackURL) {
req.Header.Add("Authorization", "Basic "+c.auth())
} else { // App or Beta
req.Header.Set("Authorization", "Bearer "+c.options.appAPIKey)
}
// Fire the request
var resp *resty.Response
switch httpMethod {
case http.MethodPost:
if resp, err = req.Post(requestURL); err != nil {
return
}
case http.MethodPut:
if resp, err = req.Put(requestURL); err != nil {
return
}
case http.MethodDelete:
if resp, err = req.Delete(requestURL); err != nil {
return
}
case http.MethodGet:
if resp, err = req.Get(requestURL); err != nil {
return
}
}
// Tracing enabled?
if c.options.requestTracing {
response.Tracing = resp.Request.TraceInfo()
}
// Set the status code & body
response.StatusCode = resp.StatusCode()
response.Body = resp.Body()
// Process if error (different error formats for different API endpoint/urls)
// The Customer.io API only responds with 200 if successful
if http.StatusOK != response.StatusCode {
if strings.Contains(requestURL, "/v1/send/email") {
var meta struct {
Meta struct {
Err string `json:"error"`
} `json:"meta"`
}
if err = json.Unmarshal(response.Body, &meta); err != nil {
err = &TransactionalError{
StatusCode: response.StatusCode,
Err: string(response.Body),
}
} else {
err = &TransactionalError{
StatusCode: response.StatusCode,
Err: meta.Meta.Err,
}
}
return
}
err = &APIError{
status: response.StatusCode,
url: requestURL,
body: response.Body,
}
}
return
}