-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpostmark.go
100 lines (83 loc) · 1.75 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
package postmark
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)
var (
postmarkURL = `https://api.postmarkapp.com`
)
const (
server_token = "server"
account_token = "account"
)
type Client struct {
HTTPClient *http.Client
ServerToken string
AccountToken string
BaseURL string
}
type parameters struct {
Method string
Path string
Payload interface{}
TokenType string
}
type APIError struct {
ErrorCode int64
Message string
}
type Postmark struct {
From string
To string
Subject string
HtmlBody string
TextBody string
}
func NewClient(serverToken string, accountToken string) *Client {
return &Client{
HTTPClient: &http.Client{},
ServerToken: serverToken,
AccountToken: accountToken,
BaseURL: postmarkURL,
}
}
func (client *Client) doRequest(opts parameters, dst interface{}) error {
url := fmt.Sprintf("%s/%s", client.BaseURL, opts.Path)
req, err := http.NewRequest(opts.Method, url, nil)
if err != nil {
return err
}
if opts.Payload != nil {
payloadData, err := json.Marshal(opts.Payload)
if err != nil {
return err
}
req.Body = io.NopCloser(bytes.NewBuffer(payloadData))
}
req.Header.Add("Accept", "application/json")
req.Header.Add("Content-Type", "application/json")
switch opts.TokenType {
case account_token:
req.Header.Add("X-Postmark-Account-Token", client.AccountToken)
default:
req.Header.Add("X-Postmark-Server-Token", client.ServerToken)
}
res, err := client.HTTPClient.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
body, err := io.ReadAll(res.Body)
if err != nil {
return err
}
err = json.Unmarshal(body, dst)
return err
}
// Error returns the error message details
func (res APIError) Error() string {
return res.Message
}