-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.go
More file actions
56 lines (45 loc) · 1.51 KB
/
client.go
File metadata and controls
56 lines (45 loc) · 1.51 KB
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
package wxsender
import (
"encoding/json"
"fmt"
"github.com/iristack/wxsender/structs"
"github.com/iristack/wxsender/types"
"io"
"net/http"
"strings"
)
const (
DefaultClientAppEndpoint = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="
DefaultClientBotEndpoint = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key="
)
type Client struct {
Type types.MessageType // 发送的消息类型
AccessToken string // 若选择APP发送, 请填写APP的access_token
Key string // 若选择Bot发送, 请填写Bot的key
UrlPrefix string // 请填写企业微信的url前缀, Bot默认为https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=, App则默认为https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=
}
func (c *Client) Create() {
if c.Type == types.ROBOT {
c.UrlPrefix = DefaultClientBotEndpoint + c.Key
} else {
c.UrlPrefix = DefaultClientAppEndpoint + c.AccessToken
}
}
func (c *Client) Submit(m structs.Completable) (structs.WxResponse, error) {
content := m.Complete()
resp, err := http.Post(c.UrlPrefix, "application/json", strings.NewReader(content))
if err != nil {
return structs.WxResponse{}, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return structs.WxResponse{}, err
}
var wxResp structs.WxResponse
err = json.Unmarshal(body, &wxResp)
if err != nil {
return structs.WxResponse{}, fmt.Errorf("解析响应失败: %v, 原始返回: %s", err, body)
}
return wxResp, nil
}