forked from shunfei/cronsun
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwework.go
72 lines (65 loc) · 1.43 KB
/
wework.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
package cronsun
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"github.com/shunfei/cronsun/log"
)
type WeWork struct {
webHook string
msgCh chan *Message
}
type markdown struct {
Content string `json:"content"`
}
type markdownMsg struct {
Msgtype string `json:"msgtype"`
Markdown markdown `json:"markdown"`
}
func NewWeWork(webHook string) *WeWork {
weWork := WeWork{
webHook: webHook,
msgCh: make(chan *Message, 8),
}
return &weWork
}
func (w *WeWork) Serve() {
for {
select {
case msg := <-w.msgCh:
log.Debugf("msg:%+v", msg)
toUsers := ""
for _, to := range msg.To {
toUsers += fmt.Sprintf("<@%s>", to)
}
mkMsg := markdownMsg{
Msgtype: "markdown",
Markdown: markdown{
Content: fmt.Sprintf("# %s\n%s\n%s", msg.Subject, msg.Body, toUsers),
},
}
data, err := json.Marshal(mkMsg)
if err != nil {
log.Errorf("json.Marshal() failed, data:%+v, err:%s", mkMsg, err)
continue
}
log.Debugf("data:%s", data)
body := bytes.NewReader(data)
log.Debugf("webHook:%s, body:%d", w.webHook, body.Len())
res, err := http.Post(w.webHook, "application/json", body)
if err != nil {
log.Errorf("http.Post() failed, url:%s, err:%s", w.webHook, err)
continue
}
if res.StatusCode != http.StatusOK {
log.Errorf("res.StatusCode:%d", res.StatusCode)
continue
}
log.Debugf("send msg success")
}
}
}
func (w *WeWork) Send(msg *Message) {
w.msgCh <- msg
}