-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmmailer.go
78 lines (68 loc) · 1.67 KB
/
mmailer.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
package mmailer
import (
"context"
"errors"
"fmt"
"io/ioutil"
"net/http"
"strings"
"time"
)
type Facade struct {
Services []Service
Selecting SelectStrategy
Retry RetryStrategy
}
func New(selecting SelectStrategy, retry RetryStrategy, services ...Service) *Facade {
return &Facade{
Services: services,
Selecting: selecting,
Retry: retry,
}
}
func (f *Facade) Send(ctx context.Context, email Email, preferredService string) (res []Response, err error) {
if len(f.Services) == 0 {
return nil, errors.New("facade no services to use")
}
var service Service
// If service is specified
if len(preferredService) > 0 {
preferredService = strings.ToLower(preferredService)
for _, s := range f.Services {
if s.Name() == preferredService {
service = s
break
}
}
}
// Regular selection strategy
if service == nil {
strategy := f.Selecting
if strategy == nil {
strategy = SelectRandom
}
service = strategy(f.Services)
}
if service == nil {
return nil, errors.New("selected service does not have a mailer associated with it")
}
retry := f.Retry
if retry == nil {
retry = RetryNone
}
fmt.Printf("[info] Sending mail to %v through %s at [%v]\n", email.To, service.Name(), time.Now().String())
return retry(ctx, service, email, f.Services)
}
func (f *Facade) UnmarshalPosthook(r *http.Request) (res []Posthook, err error) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
return nil, err
}
name := strings.ToLower(r.URL.Query().Get("service"))
for _, s := range f.Services {
if s.Name() == name {
return s.UnmarshalPosthook(body)
}
}
return nil, errors.New("could not find a service to unmarshal posthook to")
}