-
Notifications
You must be signed in to change notification settings - Fork 0
/
slack_notifier.go
124 lines (104 loc) · 2.6 KB
/
slack_notifier.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
package notiz
import (
"bytes"
"fmt"
"github.com/spf13/viper"
"github.com/w3y/notiz/utils"
"net"
"net/http"
"sync"
"time"
)
const _pressureThreshold = 800
var (
netClient = &http.Client{
Timeout: time.Second * 5,
Transport: &http.Transport{
DialContext: (&net.Dialer{
Timeout: 5 * time.Second,
KeepAlive: 5 * time.Second,
}).DialContext,
TLSHandshakeTimeout: 5 * time.Second,
ResponseHeaderTimeout: 5 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
},
}
lock sync.RWMutex
notifyPusher *slackNotifierPusher
membersPicked = make(map[string]string)
)
func NewSlackNotifyPusher() *slackNotifierPusher {
pusher := &slackNotifierPusher{
pushChan: make(chan pusherMessage, 1000),
}
go func() {
for {
select {
case <-closeChan:
return
case msg := <-pusher.pushChan:
buf := bytes.NewBuffer(msg.message)
_, err := netClient.Post(msg.webHook, "application/json", buf)
if err != nil {
//TODO: print error log
}
}
}
}()
return pusher
}
type pusherMessage struct {
webHook string
message []byte
}
type slackNotifierPusher struct {
pushChan chan pusherMessage
}
type SlackMessage struct {
TaggingMsg string `json:"pretext"`
Color string `json:"color"`
App string `json:"author_name"`
AppLink string `json:"author_link"`
NotiContent string `json:"title"`
RefLink string `json:"title_link"`
NotiDetail string `json:"text"`
Env string `json:"footer"`
Ts int64 `json:"ts"`
members []string `json:"-"`
}
func init() {
lock.Lock()
defer lock.Unlock()
if notifyPusher == nil {
notifyPusher = NewSlackNotifyPusher()
}
}
func (m *SlackMessage) Opts() map[string]string {
return map[string]string{}
}
func (m *SlackMessage) Hash() string {
return fmt.Sprintf("%s-%s-%s-%s-%s", m.Env, m.App, m.NotiContent, utils.GetMD5Hash(m.NotiDetail), m.RefLink)
}
type SlackNotifier struct {
webHook string
notifyChan chan []byte
lazyNoti bool
members []string
}
func NewSlackNotifier() *SlackNotifier {
return NewSlackNotifierCustom(viper.GetString("notifier.slack.webhook"))
}
func NewSlackCriticalNotifier() *SlackNotifier {
return NewSlackNotifierCustom(viper.GetString("notifier.critical.slack.webhook"))
}
func NewSlackNotifierCustomWithMembers(customWebhook string, members []string) *SlackNotifier {
slackNotifier := &SlackNotifier{
webHook: customWebhook,
lazyNoti: true,
members: members,
}
return slackNotifier
}
func NewSlackNotifierCustom(customWebhook string) *SlackNotifier {
return NewSlackNotifierCustomWithMembers(customWebhook, []string{})
}