-
Notifications
You must be signed in to change notification settings - Fork 0
/
service.go
91 lines (74 loc) · 1.76 KB
/
service.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
package visimail
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
)
const (
baseURL = "https://api.sendinblue.com"
apiVersion = "v3"
)
type Service struct {
defaultHeaders map[string]string
}
func NewService() *Service {
return &Service{
defaultHeaders: map[string]string{
"api-key": env.Sendinblue.ApiKey,
"Accept": "application/json",
"Content-Type": "application/json",
},
}
}
// TODO: add Service.SendChunkedEmail(ctx context.Context, email *Email, nbAttachmentsPerChunk int) (chan string, chan error)
func (s *Service) SendEmail(ctx context.Context, email *Email) (string, error) {
return s.sendEmail(ctx, email)
}
func (s *Service) sendEmail(_ context.Context, email *Email) (string, error) {
if err := email.Validate(); err != nil {
return "", err
}
payload, err := json.Marshal(email)
if err != nil {
return "", err
}
req, err := http.NewRequest(http.MethodPost, s.requestURL("/smtp/email"), bytes.NewBuffer(payload))
if err != nil {
return "", err
}
s.applyHeaders(req)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}
if isHttpError(resp.StatusCode) {
var he HttpError
if err := json.Unmarshal(body, &he); err != nil {
return "", err
}
return "", he
}
var obj struct {
MessageID string `json:"messageId"`
}
if err := json.Unmarshal(body, &obj); err != nil {
return "", err
}
return obj.MessageID, nil
}
func (s *Service) requestURL(endpoint string) string {
return fmt.Sprintf("%s/%s%s", baseURL, apiVersion, endpoint)
}
func (s *Service) applyHeaders(request *http.Request) {
for key, value := range s.defaultHeaders {
request.Header.Set(key, value)
}
}