forked from CatchZeng/dingtalk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
80 lines (65 loc) · 1.52 KB
/
client.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
package dingtalk
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"time"
"github.com/manjoc/dingtalk/internal/security"
)
// Client dingtalk client
type Client struct {
AccessToken string
Secret string
}
// NewClient new dingtalk client
func NewClient(accessToken, secret string) *Client {
return &Client{
AccessToken: accessToken,
Secret: secret,
}
}
// Response response struct
type Response struct {
ErrMsg string `json:"errmsg"`
ErrCode int64 `json:"errcode"`
}
const httpTimoutSecond = time.Duration(30) * time.Second
// Send message
func (d *Client) Send(message Message) (*Response, error) {
res := &Response{}
reqBytes, err := message.ToByte()
if err != nil {
return res, err
}
pushURL, err := security.URL(d.AccessToken, d.Secret)
if err != nil {
return res, err
}
req, err := http.NewRequest(http.MethodPost, pushURL, bytes.NewReader(reqBytes))
if err != nil {
return res, err
}
req.Header.Add("Accept-Charset", "utf8")
req.Header.Add("Content-Type", "application/json")
client := new(http.Client)
client.Timeout = httpTimoutSecond
resp, err := client.Do(req)
if err != nil {
return res, err
}
defer resp.Body.Close()
resultByte, err := ioutil.ReadAll(resp.Body)
if err != nil {
return res, err
}
err = json.Unmarshal(resultByte, &res)
if err != nil {
return res, fmt.Errorf("unmarshal http response body from json error = %v", err)
}
if res.ErrCode != 0 {
return res, fmt.Errorf("send message to dingtalk error = %s", res.ErrMsg)
}
return res, nil
}