-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.go
203 lines (167 loc) · 4.96 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
package mailosaur
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"time"
)
type MailosaurClient struct {
baseUrl string
apiKey string
userAgent string
httpClient *http.Client
Servers *ServersService
Messages *MessagesService
Analysis *AnalysisService
Files *FilesService
Usage *UsageService
Devices *DevicesService
Previews *PreviewsService
}
type mailosaurError struct {
Message string
ErrorType string
HttpStatusCode int
HttpResponseBody string
}
type ErrorDetail struct {
Description string `json:"description"`
}
type Error struct {
Field string `json:"field"`
Detail []ErrorDetail `json:"detail"`
}
type ErrorResponse struct {
Errors []Error `json:"errors"`
}
func (e *mailosaurError) Error() string {
return e.Message
}
func New(apiKey string) *MailosaurClient {
return NewWithClient(apiKey, &http.Client{Timeout: time.Minute})
}
func NewWithClient(apiKey string, httpClient *http.Client) *MailosaurClient {
c := &MailosaurClient{
baseUrl: "https://mailosaur.com/",
apiKey: apiKey,
httpClient: httpClient,
userAgent: "mailosaur-go/1.0.0",
}
c.Servers = &ServersService{client: c}
c.Messages = &MessagesService{client: c}
c.Analysis = &AnalysisService{client: c}
c.Files = &FilesService{client: c}
c.Usage = &UsageService{client: c}
c.Devices = &DevicesService{client: c}
c.Previews = &PreviewsService{client: c}
return c
}
func (c *MailosaurClient) httpRequest(method, path string, body interface{}) (*http.Request, error) {
u := c.baseUrl + path
var buf io.ReadWriter
if body != nil {
buf = new(bytes.Buffer)
err := json.NewEncoder(buf).Encode(body)
if err != nil {
return nil, err
}
}
req, err := http.NewRequest(method, u, buf)
if err != nil {
return nil, err
}
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
req.Header.Set("Accept", "application/json")
req.Header.Set("User-Agent", c.userAgent)
return req, nil
}
func (c *MailosaurClient) executeRequestWithDelayHeader(result interface{}, method string, path string, body interface{}, expectedStatus int) (interface{}, string, error) {
req, err := c.httpRequest(method, path, body)
if err != nil {
return result, "", err
}
req.SetBasicAuth(c.apiKey, "")
resp, err := c.httpClient.Do(req)
if err != nil {
return result, "", err
}
defer resp.Body.Close()
if resp.StatusCode != expectedStatus {
err := &mailosaurError{}
err.HttpStatusCode = resp.StatusCode
var bodyBytes []byte
if err.HttpStatusCode != 204 {
bodyBytes, _ = io.ReadAll(resp.Body)
err.HttpResponseBody = string(bodyBytes)
}
message := ""
switch resp.StatusCode {
case 400:
var jsonResult ErrorResponse
json.Unmarshal(bodyBytes, &jsonResult)
for _, e := range jsonResult.Errors {
message += fmt.Sprintf("(%s) %s\r\n", e.Field, e.Detail[0].Description)
}
err.Message = message
err.ErrorType = "invalid_request"
case 401:
err.Message = "Authentication failed, check your API key."
err.ErrorType = "authentication_error"
case 403:
err.Message = "Insufficient permission to perform that task."
err.ErrorType = "permission_error"
case 404:
err.Message = "Not found, check input parameters."
err.ErrorType = "invalid_request"
default:
err.Message = "An API error occurred, see httpResponse for further information."
err.ErrorType = "api_error"
break
}
return result, "", err
}
// If no result type is being marshalled, just return the bytes
if result == nil {
bodyBytes, err := io.ReadAll(resp.Body)
return bodyBytes, resp.Header.Get("x-ms-delay"), err
}
err = json.NewDecoder(resp.Body).Decode(&result)
return result, resp.Header.Get("x-ms-delay"), err
}
func (c *MailosaurClient) executeRequest(result interface{}, method string, path string, body interface{}, expectedStatus int) (interface{}, error) {
result, _, err := c.executeRequestWithDelayHeader(result, method, path, body, expectedStatus)
return result, err
}
func (c *MailosaurClient) HttpPost(result interface{}, path string, body interface{}) (interface{}, error) {
return c.executeRequest(result, "POST", path, body, 200)
}
func (c *MailosaurClient) HttpGet(result interface{}, path string) (interface{}, error) {
return c.executeRequest(result, "GET", path, nil, 200)
}
func (c *MailosaurClient) HttpPut(result interface{}, path string, body interface{}) (interface{}, error) {
return c.executeRequest(result, "PUT", path, body, 200)
}
func (c *MailosaurClient) HttpDelete(path string) error {
_, err := c.executeRequest(nil, "DELETE", path, nil, 204)
return err
}
func buildPagePath(path string, page int, itemsPerPage int, receivedAfter time.Time, dir string) string {
if page > 0 {
path += "&page=" + fmt.Sprint(page)
}
if itemsPerPage > 0 {
path += "&itemsPerPage=" + fmt.Sprint(itemsPerPage)
}
if !receivedAfter.IsZero() {
path += "&receivedAfter=" + url.QueryEscape(receivedAfter.Format(time.RFC3339))
}
if len(dir) > 0 {
path += "&dir=" + dir
}
return path
}