-
Notifications
You must be signed in to change notification settings - Fork 0
/
postmark.go
204 lines (165 loc) · 4.38 KB
/
postmark.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
package postmark
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
"strings"
"time"
"golang.org/x/net/context"
)
const (
apiHost = "api.postmarkapp.com"
serverTokenHeader = "X-Postmark-Server-Token"
accountTokenHeader = "X-Postmark-Account-Token"
)
// Postmark defines methods to interace with the Postmark API
type Postmark interface {
SetClient(client *http.Client) Postmark
// Templates returns a resource root object handling template interactions with Postmark
Templates() Templates
// Templates returns a resource root object handling template interactions with Postmark
Emails() Emails
}
type postmark struct {
serverToken string
accountToken string
scheme string
host string
client *http.Client
}
// Request is an general container for requests sent with Postmark
type Request struct {
Method string
Path string
Params url.Values
Payload interface{}
Target interface{}
// Set this to true in order to use the account-wide API token
AccountAuth bool
}
// New returns an initialized Postmark client
func New(serverToken, accountToken string) Postmark {
return &postmark{
serverToken: serverToken,
accountToken: accountToken,
scheme: "https",
host: apiHost,
}
}
func (p *postmark) Templates() Templates {
return &templates{pm: p}
}
func (p *postmark) Emails() Emails {
return &emails{pm: p}
}
func (p *postmark) Exec(ctx context.Context, req *Request) (*http.Response, error) {
var payload io.Reader
if req.Payload != nil {
data, err := json.Marshal(req.Payload)
if err != nil {
return nil, err
}
payload = bytes.NewReader(data)
}
urlBuilder := url.URL{
Scheme: p.scheme,
Host: p.host,
Path: req.Path,
RawQuery: req.Params.Encode(), // returns "" if nil
}
r, err := http.NewRequest(req.Method, urlBuilder.String(), payload)
if err != nil {
return nil, err
}
r.Header.Set("Accept", "application/json")
r.Header.Set("Content-Type", "application/json")
if req.AccountAuth {
r.Header.Set(accountTokenHeader, p.accountToken)
} else {
r.Header.Set(serverTokenHeader, p.serverToken)
}
resp, err := p.httpclient().Do(r)
if err != nil {
return nil, err
}
defer resp.Body.Close()
// for unsuccessful http status codes, unmarshal an error
if resp.StatusCode/100 != 2 {
pmerr := &Error{StatusCode: resp.StatusCode}
// handle non-json responses
if !strings.Contains(resp.Header.Get("Content-Type"), "application/json") {
log.Printf("req: %+v", r)
respData, _ := ioutil.ReadAll(resp.Body)
pmerr.Message = string(respData)
return resp, pmerr
}
if err := json.NewDecoder(resp.Body).Decode(pmerr); err != nil {
return resp, err
}
if pmerr.IsError() {
return resp, pmerr
}
return resp, fmt.Errorf("postmark call errored with status: %d", resp.StatusCode)
}
if req.Target != nil {
if err := json.NewDecoder(resp.Body).Decode(req.Target); err != nil {
return nil, err
}
}
return resp, nil
}
func (p *postmark) httpclient() *http.Client {
if p.client != nil {
return p.client
}
return http.DefaultClient
}
func (p *postmark) SetClient(client *http.Client) Postmark {
p.client = client
return p
}
// Error defines an error from the Postmark API
type Error struct {
ErrorCode int
Message string
// the HTTP status code of the response itself
StatusCode int `json:"-"`
}
// IsError returns whether or not the response indicated an error
func (e *Error) IsError() bool {
return e.ErrorCode != 0
}
func (e *Error) Error() string {
if e.ErrorCode == 0 {
return fmt.Sprintf("postmark HTTP error %d: %s", e.StatusCode, e.Message)
}
codeMeaning := "unknown"
if meaning, ok := ErrorLookup[e.ErrorCode]; ok {
codeMeaning = meaning
}
return fmt.Sprintf("postmark error %d %s: %s", e.ErrorCode, e.Message, codeMeaning)
}
// Time wraps time.Time with more flexible parsing. It has only been necessary in a few cases,
// using the stdlib's time.Time is preferred if possible.
type Time time.Time
const (
rfc3339NoTz = "2006-01-02T15:04:05"
)
// UnmarshalJSON implements more flexible parsing of timestamps for the Time type
func (t *Time) UnmarshalJSON(data []byte) error {
if err := (*time.Time)(t).UnmarshalJSON(data); err == nil {
// if the default parsing works then we have nothing to do
return nil
}
stdtime, err := time.Parse(`"`+rfc3339NoTz+`"`, string(data))
if err != nil {
return err
}
*t = (Time)(stdtime)
return nil
}