-
Notifications
You must be signed in to change notification settings - Fork 0
/
delivery.go
106 lines (94 loc) · 2.46 KB
/
delivery.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
package loggerdelivery
import (
"encoding/json"
"errors"
"fmt"
"math/rand"
"time"
"github.com/herb-go/logger"
"github.com/herb-go/notification"
"github.com/herb-go/notification/notificationdelivery"
)
type Delivery struct {
logger *logger.Logger
delayMin time.Duration
delayMax time.Duration
failPercent int
errorPercent int
}
func (d *Delivery) DeliveryType() string {
return DeliveryType
}
//CheckInvalidContent check if given content invalid
//Return invalid fields and any error raised
func (d *Delivery) CheckInvalidContent(notification.Content) ([]string, error) {
return []string{}, nil
}
func (d *Delivery) Deliver(c notification.Content) (notificationdelivery.DeliveryStatus, string, error) {
bs, err := json.Marshal(c)
if err != nil {
return notificationdelivery.DeliveryStatusAbort, "", err
}
delay := rand.Int63n(int64(d.delayMax - d.delayMin))
time.Sleep(time.Duration(delay))
if rand.Int31n(100) <= int32(d.failPercent) {
return notificationdelivery.DeliveryStatusFail, "fail", nil
}
if rand.Int31n(100) <= int32(d.errorPercent) {
return notificationdelivery.DeliveryStatusFail, "", errors.New("random error")
}
d.logger.Log(fmt.Sprintf("mock: %s", string(bs)))
return notificationdelivery.DeliveryStatusSuccess, "", nil
}
func (d *Delivery) MustEscape(unescaped string) string {
return unescaped
}
//ContentFields return content fields
//Return invalid fields and any error raised
func (d Delivery) ContentFields() []*notificationdelivery.Field {
return nil
}
type Config struct {
Logger string
DelayMinDuration string
DelayMaxDuration string
FailPercent int
ErrorPercent int
}
var Factory = func(loader func(interface{}) error) (notificationdelivery.DeliveryDriver, error) {
c := &Config{}
err := loader(c)
if err != nil {
return nil, err
}
l := logger.GetBuiltinLogger(c.Logger)
if l == nil {
return nil, fmt.Errorf("builtin logger [%s] not found", c.Logger)
}
d := &Delivery{
logger: l,
failPercent: c.FailPercent,
errorPercent: c.ErrorPercent,
}
if c.DelayMinDuration != "" {
dmin, err := time.ParseDuration(c.DelayMinDuration)
if err != nil {
return nil, err
}
d.delayMin = dmin
}
if c.DelayMaxDuration != "" {
dmax, err := time.ParseDuration(c.DelayMaxDuration)
if err != nil {
return nil, err
}
d.delayMax = dmax
}
if d.delayMax < d.delayMin {
d.delayMax = d.delayMin
}
return d, nil
}
func init() {
notificationdelivery.Register(DeliveryType, Factory)
}