/
webhook.go
71 lines (61 loc) · 1.5 KB
/
webhook.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
package webhook
import (
"fmt"
"sync"
"time"
)
var (
receiverMu sync.RWMutex
receivers = make(map[string]WebhookReceiver)
// Based on the local test, Teams sometimes cannot finish the request in 1 second, so use 3s.
timeout = 3 * time.Second
timeFormat = "2006-01-02 15:04:05"
)
type WebhookMeta struct {
Name string
Value string
}
type WebhookLevel string
const (
WebhookInfo WebhookLevel = "INFO"
WebhookSuccess WebhookLevel = "SUCCESS"
WebhookWarn WebhookLevel = "WARN"
WebhookError WebhookLevel = "ERROR"
)
type WebhookContext struct {
URL string
Level WebhookLevel
Title string
Description string
Link string
CreatorName string
CreatorEmail string
CreatedTs int64
MetaList []WebhookMeta
}
type WebhookReceiver interface {
post(context WebhookContext) error
}
// Register makes a receiver available by the url host
// If Register is called twice with the same url host or if receiver is nil,
// it panics.
func register(host string, r WebhookReceiver) {
receiverMu.Lock()
defer receiverMu.Unlock()
if r == nil {
panic("webhook: Register receiver is nil")
}
if _, dup := receivers[host]; dup {
panic("webhook: Register called twice for host " + host)
}
receivers[host] = r
}
func Post(webhookType string, context WebhookContext) error {
receiverMu.RLock()
r, ok := receivers[webhookType]
receiverMu.RUnlock()
if !ok {
return fmt.Errorf("webhook: no applicable receiver for webhook type: %v", webhookType)
}
return r.post(context)
}