-
Notifications
You must be signed in to change notification settings - Fork 260
/
sendgrid.go
90 lines (78 loc) · 2.4 KB
/
sendgrid.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
package sendgrid
import (
"errors"
"github.com/sendgrid/rest"
"net/url"
)
// sendGridOptions for CreateRequest
type sendGridOptions struct {
Key string
Endpoint string
Host string
Subuser string
}
// sendgrid host map for different regions
var allowedRegionsHostMap = map[string]string{
"eu": "https://api.eu.sendgrid.com",
"global": "https://api.sendgrid.com",
}
// GetRequest
// @return [Request] a default request object
func GetRequest(key, endpoint, host string) rest.Request {
return createSendGridRequest(sendGridOptions{key, endpoint, host, ""})
}
// GetRequestSubuser like GetRequest but with On-Behalf of Subuser
// @return [Request] a default request object
func GetRequestSubuser(key, endpoint, host, subuser string) rest.Request {
return createSendGridRequest(sendGridOptions{key, endpoint, host, subuser})
}
// createSendGridRequest create Request
// @return [Request] a default request object
func createSendGridRequest(sgOptions sendGridOptions) rest.Request {
options := options{
"Bearer " + sgOptions.Key,
sgOptions.Endpoint,
sgOptions.Host,
sgOptions.Subuser,
}
if options.Host == "" {
options.Host = "https://api.sendgrid.com"
}
return requestNew(options)
}
// NewSendClient constructs a new Twilio SendGrid client given an API key
func NewSendClient(key string) *Client {
request := GetRequest(key, "/v3/mail/send", "")
request.Method = "POST"
return &Client{request}
}
// extractEndpoint extracts the endpoint from a baseURL
func extractEndpoint(link string) (string, error) {
parsedURL, err := url.Parse(link)
if err != nil {
return "", err
}
return parsedURL.Path, nil
}
// SetDataResidency modifies the host as per the region
/*
* This allows support for global and eu regions only. This set will likely expand in the future.
* Global should be the default
* Global region means the message should be sent through:
* HTTP: api.sendgrid.com
* EU region means the message should be sent through:
* HTTP: api.eu.sendgrid.com
*/
// @return [Request] the modified request object
func SetDataResidency(request rest.Request, region string) (rest.Request, error) {
regionalHost, present := allowedRegionsHostMap[region]
if !present {
return request, errors.New("error: region can only be \"eu\" or \"global\"")
}
endpoint, err := extractEndpoint(request.BaseURL)
if err != nil {
return request, err
}
request.BaseURL = regionalHost + endpoint
return request, nil
}