-
Notifications
You must be signed in to change notification settings - Fork 164
/
webhook_client.go
85 lines (67 loc) · 1.67 KB
/
webhook_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
81
82
83
84
85
package workwx
import (
"bytes"
"encoding/json"
"fmt"
"net/url"
)
// WebhookClient 群机器人客户端
type WebhookClient struct {
opts options
key string
}
// NewWebhookClient 构造一个群机器人客户端对象,需要提供 webhook 的 key。
func NewWebhookClient(key string, opts ...CtorOption) *WebhookClient {
optionsObj := defaultOptions()
for _, o := range opts {
o.applyTo(&optionsObj)
}
return &WebhookClient{
opts: optionsObj,
key: key,
}
}
// Key 返回该群机器人客户端所配置的 webhook key。
func (c *WebhookClient) Key() string {
return c.key
}
func (c *WebhookClient) composeQyapiURLWithKey(path string, req interface{}) (*url.URL, error) {
values := url.Values{}
if valuer, ok := req.(urlValuer); ok {
values = valuer.intoURLValues()
}
// add webhook key
values.Set("key", c.key)
// TODO: refactor
base, err := url.Parse(c.opts.QYAPIHost)
if err != nil {
return nil, fmt.Errorf("qyapiHost invalid: host=%s err=%w", c.opts.QYAPIHost, err)
}
base.Path = path
base.RawQuery = values.Encode()
return base, nil
}
func (c *WebhookClient) executeQyapiJSONPost(path string, req interface{}, respObj interface{}) error {
url, err := c.composeQyapiURLWithKey(path, req)
if err != nil {
return err
}
urlStr := url.String()
body, err := json.Marshal(req)
if err != nil {
return makeReqMarshalErr(err)
}
resp, err := c.opts.HTTP.Post(urlStr, "application/json", bytes.NewReader(body))
if err != nil {
return makeRequestErr(err)
}
defer resp.Body.Close()
if respObj != nil {
decoder := json.NewDecoder(resp.Body)
err = decoder.Decode(respObj)
if err != nil {
return makeRespUnmarshalErr(err)
}
}
return nil
}