-
Notifications
You must be signed in to change notification settings - Fork 4
/
mailersend.go
293 lines (246 loc) · 7.47 KB
/
mailersend.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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
package mailersend
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"reflect"
"github.com/google/go-querystring/query"
)
const APIBase string = "https://api.mailersend.com/v1"
// Mailersend - base mailersend api client
type Mailersend struct {
apiBase string
apiKey string
client *http.Client
common service // Reuse a single struct.
// Services
Activity *ActivityService
Analytics *AnalyticsService
Domain *DomainService
Email *EmailService
BulkEmail *BulkEmailService
Message *MessageService
ScheduleMessage *ScheduleMessageService
Recipient *RecipientService
Template *TemplateService
Token *TokenService
Webhook *WebhookService
Suppression *SuppressionService
Inbound *InboundService
Sms *SmsService
SmsActivity *SmsActivityService
SmsNumber *SmsNumberService
SmsRecipient *SmsRecipientService
SmsWebhook *SmsWebhookService
SmsMessage *SmsMessageService
SmsInbound *SmsInboundService
EmailVerification *EmailVerificationService
Identity *IdentityService
ApiQuota *ApiQuotaService
}
type service struct {
client *Mailersend
}
// Response is a Mailersend API response. This wraps the standard http.Response
// returned from Mailersend and provides convenient access to things like
// pagination links.
type Response struct {
*http.Response
}
type ErrorResponse struct {
Response *http.Response // HTTP response that caused this error
Message string `json:"message"` // error message
}
func (r *ErrorResponse) Error() string {
return fmt.Sprintf("%v %v: %d %v",
r.Response.Request.Method, r.Response.Request.URL,
r.Response.StatusCode, r.Message)
}
// AuthError occurs when using HTTP Authentication fails
type AuthError ErrorResponse
func (r *AuthError) Error() string { return (*ErrorResponse)(r).Error() }
// Meta - used for api responses
type Meta struct {
CurrentPage json.Number `json:"current_page"`
From json.Number `json:"from"`
Path string `json:"path"`
PerPage json.Number `json:"per_page"`
To json.Number `json:"to"`
}
// Links - used for api responses
type Links struct {
First string `json:"first"`
Last string `json:"last"`
Prev string `json:"prev"`
Next string `json:"next"`
}
// Filter - used to filter resources
type Filter struct {
Comparer string `json:"comparer"`
Value string `json:"value"`
Key string `json:"key,omitempty"`
}
// NewMailersend - creates a new client instance.
func NewMailersend(apiKey string) *Mailersend {
ms := &Mailersend{
apiBase: APIBase,
apiKey: apiKey,
client: http.DefaultClient,
}
ms.common.client = ms
ms.Activity = (*ActivityService)(&ms.common)
ms.Analytics = (*AnalyticsService)(&ms.common)
ms.Domain = (*DomainService)(&ms.common)
ms.Email = (*EmailService)(&ms.common)
ms.BulkEmail = (*BulkEmailService)(&ms.common)
ms.Message = (*MessageService)(&ms.common)
ms.ScheduleMessage = (*ScheduleMessageService)(&ms.common)
ms.Recipient = (*RecipientService)(&ms.common)
ms.Template = (*TemplateService)(&ms.common)
ms.Token = (*TokenService)(&ms.common)
ms.Webhook = (*WebhookService)(&ms.common)
ms.Suppression = (*SuppressionService)(&ms.common)
ms.Inbound = (*InboundService)(&ms.common)
ms.Sms = (*SmsService)(&ms.common)
ms.SmsActivity = (*SmsActivityService)(&ms.common)
ms.SmsNumber = (*SmsNumberService)(&ms.common)
ms.SmsRecipient = (*SmsRecipientService)(&ms.common)
ms.SmsWebhook = (*SmsWebhookService)(&ms.common)
ms.SmsMessage = (*SmsMessageService)(&ms.common)
ms.SmsInbound = (*SmsInboundService)(&ms.common)
ms.EmailVerification = (*EmailVerificationService)(&ms.common)
ms.Identity = (*IdentityService)(&ms.common)
ms.ApiQuota = (*ApiQuotaService)(&ms.common)
return ms
}
// APIKey - Get api key after it has been created
func (ms *Mailersend) APIKey() string {
return ms.apiKey
}
// Client - Get the current client
func (ms *Mailersend) Client() *http.Client {
return ms.client
}
// SetClient - Set the client if you want more control over the client implementation
func (ms *Mailersend) SetClient(c *http.Client) {
ms.client = c
}
// SetAPIKey - Set the client api key
func (ms *Mailersend) SetAPIKey(apikey string) {
ms.apiKey = apikey
}
func (ms *Mailersend) newRequest(method, path string, body interface{}) (*http.Request, error) {
reqURL := fmt.Sprintf("%s%s", ms.apiBase, path)
reqBodyBytes := new(bytes.Buffer)
if method == http.MethodPost ||
method == http.MethodPut ||
method == http.MethodDelete {
err := json.NewEncoder(reqBodyBytes).Encode(body)
if err != nil {
return nil, err
}
} else if method == http.MethodGet {
reqURL, _ = addOptions(reqURL, body)
}
req, err := http.NewRequest(method, reqURL, reqBodyBytes)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Add("Authorization", "Bearer "+ms.apiKey)
req.Header.Set("Accept", "application/json")
req.Header.Set("User-Agent", "Mailersend-Client-Golang-v1")
return req, nil
}
func (ms *Mailersend) do(ctx context.Context, req *http.Request, v interface{}) (*Response, error) {
req = req.WithContext(ctx)
resp, err := ms.client.Do(req)
if err != nil {
select {
case <-ctx.Done():
return nil, ctx.Err()
default:
}
return nil, err
}
if v != nil {
err = json.NewDecoder(resp.Body).Decode(v)
if err != nil {
return nil, err
}
}
response := newResponse(resp)
err = CheckResponse(resp)
if err != nil {
defer resp.Body.Close()
_, readErr := io.ReadAll(resp.Body)
if readErr != nil {
return response, readErr
}
}
return response, err
}
// newResponse creates a new Response for the provided http.Response.
// r must not be nil.
func newResponse(r *http.Response) *Response {
response := &Response{Response: r}
return response
}
// CheckResponse checks the API response for errors, and returns them if
// present. A response is considered an error if it has a status code outside
// the 200 range or equal to 202 Accepted.
func CheckResponse(r *http.Response) error {
if r.StatusCode == http.StatusAccepted {
return nil
}
if c := r.StatusCode; 200 <= c && c <= 299 {
return nil
}
errorResponse := &ErrorResponse{Response: r}
data, err := io.ReadAll(r.Body)
if err == nil && data != nil {
json.Unmarshal(data, errorResponse)
}
switch {
case r.StatusCode == http.StatusUnauthorized:
return (*AuthError)(errorResponse)
default:
return errorResponse
}
}
func addOptions(s string, opt interface{}) (string, error) {
v := reflect.ValueOf(opt)
if v.Kind() == reflect.Ptr && v.IsNil() {
return s, nil
}
origURL, err := url.Parse(s)
if err != nil {
return s, err
}
origValues := origURL.Query()
newValues, err := query.Values(opt)
if err != nil {
return s, err
}
for k, v := range newValues {
origValues[k] = v
}
origURL.RawQuery = origValues.Encode()
return origURL.String(), nil
}
// Bool is a helper routine that allocates a new bool value
// to store v and returns a pointer to it.
func Bool(v bool) *bool { return &v }
// Int is a helper routine that allocates a new int value
// to store v and returns a pointer to it.
func Int(v int) *int { return &v }
// Int64 is a helper routine that allocates a new int64 value
// to store v and returns a pointer to it.
func Int64(v int64) *int64 { return &v }
// String is a helper routine that allocates a new string value
// to store v and returns a pointer to it.
func String(v string) *string { return &v }