-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.go
131 lines (104 loc) · 2.4 KB
/
server.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
package postmark
import (
"bytes"
"context"
"encoding/json"
"io/ioutil"
"net/http"
"time"
)
const (
PostmarkAPI = "https://api.postmarkapp.com"
EndpointEmail = PostmarkAPI + "/email"
EndpointEmailWithTemplate = PostmarkAPI + "/email/withTemplate"
EndpointBatch = PostmarkAPI + "/email/batch"
EndpointBatchWithTemplate = PostmarkAPI + "/email/batchWithTemplates"
)
// Server ...
type Server struct {
Token string
}
// Send ...
func (s *Server) Send(ctx context.Context, email Email) (Response, error) {
data, err := json.Marshal(email)
if err != nil {
return Response{}, err
}
endpoint := EndpointEmail
if email.UsesTemplate() {
endpoint = EndpointEmailWithTemplate
}
// Make Postmark request
body := bytes.NewReader(data)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, body)
if err != nil {
return Response{}, err
}
// Send and get response
resData, err := s.send(req)
if err != nil {
return Response{}, err
}
response := Response{}
err = json.Unmarshal(resData, &response)
if err != nil {
return Response{}, err
}
return response, nil
}
// SendBatch ...
func (s *Server) SendBatch(ctx context.Context, emails ...Email) ([]Response, error) {
if len(emails) == 0 {
return nil, nil
}
messages := map[string][]Email{
"Messages": emails,
}
data, err := json.Marshal(messages)
if err != nil {
return nil, err
}
endpoint := EndpointBatch
if emails[0].UsesTemplate() {
endpoint = EndpointBatchWithTemplate
}
// Make Postmark request
body := bytes.NewReader(data)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, body)
if err != nil {
return nil, err
}
// Send and get response
resData, err := s.send(req)
if err != nil {
return nil, err
}
responses := []Response{}
err = json.Unmarshal(resData, &responses)
if err != nil {
return nil, err
}
return responses, nil
}
func (s *Server) send(req *http.Request) ([]byte, error) {
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Accept", "application/json")
req.Header.Add("X-Postmark-Server-Token", s.Token)
client := &http.Client{
Timeout: 10 * time.Second,
}
res, err := client.Do(req)
if err != nil {
return nil, err
}
resData, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, err
}
// Close body
err = res.Body.Close()
if err != nil {
return nil, err
}
return resData, nil
}