forked from gladmo/dingbot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrequest.go
94 lines (77 loc) · 1.81 KB
/
request.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
package dingbot
import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strings"
"time"
"github.com/pkg/errors"
)
const dingTalkHost = `https://oapi.dingtalk.com`
// DingTalk client
type DingTalk struct {
AccessToken string
Secret string
}
// New ding talk client
func New(accessToken, secret string) *DingTalk {
return &DingTalk{
AccessToken: accessToken,
Secret: secret,
}
}
// getURL 构造请求地址
func (th *DingTalk) getURL() (URL string) {
URL = fmt.Sprintf("%s/robot/send?access_token=%s", dingTalkHost, th.AccessToken)
if th.Secret != "" {
ts := time.Now().UnixNano() / 1e6
stringToSign := fmt.Sprintf("%d\n%s", ts, th.Secret)
mac := hmac.New(sha256.New, []byte(th.Secret))
mac.Write([]byte(stringToSign))
signData := mac.Sum(nil)
base64sign := base64.StdEncoding.EncodeToString(signData)
URL += fmt.Sprintf("×tamp=%d&sign=%s", ts, url.QueryEscape(base64sign))
}
return
}
// Send 发送钉钉消息
func (th DingTalk) Send(msg Message) (err error) {
req, err := http.NewRequest("POST", th.getURL(), strings.NewReader(msg.String()))
if err != nil {
return
}
req.Header.Add("Content-Type", "application/json")
res, err := http.DefaultTransport.RoundTrip(req)
if err != nil {
return
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
err = fmt.Errorf("status not ok, code: %d", res.StatusCode)
return
}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return
}
var r dingRes
err = json.Unmarshal(body, &r)
if err != nil {
return
}
if r.ErrMsg != "ok" {
err = errors.New(fmt.Sprintf("Ding ding send error. res: %s", string(body)))
return
}
return
}
// dingRes 钉钉返回结果
type dingRes struct {
ErrCode int `json:"errcode"`
ErrMsg string `json:"errmsg"`
}