-
Notifications
You must be signed in to change notification settings - Fork 0
/
ding.go
124 lines (115 loc) · 2.57 KB
/
ding.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 alarm
import (
"bytes"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"github.com/jesseincn/utils/log"
"go.uber.org/zap"
"io/ioutil"
"net/http"
"strings"
"sync"
"time"
)
const ding_url = "https://oapi.dingtalk.com/robot/send?access_token="
type Ding struct {
lock sync.Mutex
token string // 钉钉告警群token
timeMap map[string]time.Time // 时间字典,记录各个模块最近发送警告的时间
span int // 同一个模块发送钉钉消息的时间间隔,单位为秒
}
func NewDing(token string, span int) *Ding {
return &Ding{
token: token,
timeMap: make(map[string]time.Time),
span: span,
}
}
func (d *Ding) Send(module, msg string, phone ...string) error {
if module == "" {
return errors.New("module is empty")
}
var can bool
d.lock.Lock()
v, ok := d.timeMap[module]
d.lock.Unlock()
if ok {
if time.Now().Sub(v).Seconds() > float64(d.span) {
can = true
} else {
log.Logger.Info("this msg is passed", zap.String("module", module), zap.String("msg", msg))
return nil
}
} else {
can = true
}
if can {
if strings.Contains(module, "【") || strings.Contains(module, "[") {
msg = fmt.Sprintf("%s%s", module, msg)
}
err := d.send(msg, phone, d.token)
if err != nil {
log.Logger.Error("d.send", zap.Error(err))
return err
}
d.lock.Lock()
d.timeMap[module] = time.Now()
d.lock.Unlock()
}
return nil
}
func (d *Ding) send(msg string, phones []string, token string) error {
ms := Message{
MsgType: "text",
Text: Texts{
Content: msg,
},
At: Ats{
AtMobiles: phones,
IsAtAll: false,
},
}
para, _ := json.Marshal(ms)
req, err := http.NewRequest("POST", ding_url+token, bytes.NewReader([]byte(para)))
if err != nil {
return err
}
req.Header.Add("Content-Type", "application/json")
var tpt = &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client := &http.Client{
Transport: tpt,
Timeout: time.Duration(10000) * time.Millisecond,
}
resp, err := client.Do(req)
if err != nil {
return err
}
data, err := ioutil.ReadAll(resp.Body)
defer resp.Body.Close()
r := &Rsp{}
_ = json.Unmarshal(data, r)
if r.Errcode != 0 {
return errors.New(r.Errmsg)
}
return nil
}
type Texts struct {
Content string `json:"content"`
}
type Ats struct {
AtMobiles []string `json:"atMobiles"`
IsAtAll bool `json:"isAtAll"`
}
type Message struct {
MsgType string `json:"msgtype"`
Text Texts `json:"text"`
At Ats `json:"at"`
}
type Rsp struct {
Errmsg string `json:"errmsg"`
Errcode int `json:"errcode"`
}