-
Notifications
You must be signed in to change notification settings - Fork 9
/
resend.go
184 lines (153 loc) · 4.13 KB
/
resend.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
package resend
import (
"bytes"
"context"
"encoding/json"
"errors"
"io"
"net/http"
"net/url"
"strings"
)
const (
version = "2.13.0"
userAgent = "resend-go/" + version
contentType = "application/json"
)
var defaultBaseURL = getEnv("RESEND_BASE_URL", "https://api.resend.com/")
// Client handles communication with Resend API.
type Client struct {
// HTTP client
client *http.Client
// Api Key
ApiKey string
// Base URL
BaseURL *url.URL
// User agent for client
UserAgent string
// HTTP headers
headers map[string]string
// Services
Emails EmailsSvc
Batch BatchSvc
ApiKeys ApiKeysSvc
Domains DomainsSvc
Audiences AudiencesSvc
Contacts ContactsSvc
}
// NewClient is the default client constructor
func NewClient(apiKey string) *Client {
key := strings.Trim(strings.TrimSpace(apiKey), "'")
return NewCustomClient(http.DefaultClient, key)
}
// NewCustomClient builds a new Resend API client, using a provided Http client.
func NewCustomClient(httpClient *http.Client, apiKey string) *Client {
if httpClient == nil {
httpClient = http.DefaultClient
}
baseURL, _ := url.Parse(defaultBaseURL)
c := &Client{client: httpClient, BaseURL: baseURL, UserAgent: userAgent}
c.Emails = &EmailsSvcImpl{client: c}
c.Batch = &BatchSvcImpl{client: c}
c.ApiKeys = &ApiKeysSvcImpl{client: c}
c.Domains = &DomainsSvcImpl{client: c}
c.Audiences = &AudiencesSvcImpl{client: c}
c.Contacts = &ContactsSvcImpl{client: c}
c.ApiKey = apiKey
c.headers = make(map[string]string)
return c
}
// NewRequest builds and returns a new HTTP request object
// based on the given arguments
func (c *Client) NewRequest(ctx context.Context, method, path string, params interface{}) (*http.Request, error) {
u, err := c.BaseURL.Parse(path)
if err != nil {
return nil, err
}
var req *http.Request
req, err = http.NewRequestWithContext(ctx, method, u.String(), nil)
if params != nil {
buf := new(bytes.Buffer)
err = json.NewEncoder(buf).Encode(params)
if err != nil {
return nil, err
}
req.Body = io.NopCloser(buf)
req.Header.Set("Content-Type", contentType)
}
for k, v := range c.headers {
req.Header.Add(k, v)
}
req.Header.Set("Accept", contentType)
req.Header.Set("User-Agent", c.UserAgent)
req.Header.Set("Authorization", "Bearer "+c.ApiKey)
return req, nil
}
// Perform sends the request to the Resend API
func (c *Client) Perform(req *http.Request, ret interface{}) (*http.Response, error) {
resp, err := c.client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
// Handle possible errors.
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated {
return nil, handleError(resp)
}
if resp.StatusCode != http.StatusNoContent && ret != nil {
if w, ok := ret.(io.Writer); ok {
_, err = io.Copy(w, resp.Body)
if err != nil {
return nil, err
}
} else {
if resp.Body != nil {
err = json.NewDecoder(resp.Body).Decode(ret)
if err != nil {
return nil, err
}
}
}
}
return resp, err
}
// handleError tries to handle errors based on HTTP status codes
func handleError(resp *http.Response) error {
switch resp.StatusCode {
// Handles errors most likely caused by the client
case http.StatusUnprocessableEntity, http.StatusBadRequest:
r := &InvalidRequestError{}
if strings.HasPrefix(resp.Header.Get("Content-Type"), "application/json") {
err := json.NewDecoder(resp.Body).Decode(r)
if err != nil {
r.Message = resp.Status
}
} else {
r.Message = resp.Status
}
return errors.New("[ERROR]: " + r.Message)
default:
// Tries to parse `message` attr from error
r := &DefaultError{}
if strings.HasPrefix(resp.Header.Get("Content-Type"), "application/json") {
err := json.NewDecoder(resp.Body).Decode(r)
if err != nil {
r.Message = resp.Status
}
} else {
r.Message = resp.Status
}
if r.Message != "" {
return errors.New("[ERROR]: " + r.Message)
}
return errors.New("[ERROR]: Unknown Error")
}
}
type InvalidRequestError struct {
StatusCode int `json:"statusCode"`
Name string `json:"name"`
Message string `json:"message"`
}
type DefaultError struct {
Message string `json:"message"`
}