@@ -14,11 +14,9 @@ type Bot struct {
14
14
webhookURL string
15
15
key string
16
16
17
- threadSafe bool
18
- reqbuf , resbuf * bytes.Buffer
19
- client * http.Client
20
- marshal func (v interface {}) ([]byte , error )
21
- unmarshal func (data []byte , v interface {}) error
17
+ threadSafe bool
18
+ reqbuf * bytes.Buffer
19
+ client * http.Client
22
20
}
23
21
24
22
// NewBot 返回企业微信群机器人实例
@@ -27,8 +25,6 @@ func NewBot(key string, opts ...func(*Bot)) *Bot {
27
25
webhookURL : fmt .Sprintf ("https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=%s" , key ),
28
26
key : key ,
29
27
client : http .DefaultClient ,
30
- marshal : json .Marshal ,
31
- unmarshal : json .Unmarshal ,
32
28
}
33
29
34
30
for _ , setter := range opts {
@@ -37,7 +33,6 @@ func NewBot(key string, opts ...func(*Bot)) *Bot {
37
33
38
34
if ! bot .threadSafe {
39
35
bot .reqbuf = bytes .NewBuffer (nil )
40
- bot .resbuf = bytes .NewBuffer (nil )
41
36
}
42
37
43
38
return & bot
@@ -57,39 +52,23 @@ func WithHttpClient(c *http.Client) func(*Bot) {
57
52
}
58
53
}
59
54
60
- // WithMarshal 设置序列化函数实现
61
- func WithMarshal (f func (v interface {}) ([]byte , error )) func (* Bot ) {
62
- return func (bot * Bot ) {
63
- bot .marshal = f
64
- }
65
- }
66
-
67
- // WithUnmarshal 设置反序列化函数实现
68
- func WithUnmarshal (f func (data []byte , v interface {}) error ) func (* Bot ) {
69
- return func (bot * Bot ) {
70
- bot .unmarshal = f
71
- }
72
- }
73
-
74
55
var jsonReqHeader = map [string ]string {
75
56
"Content-Type" : "application/json" ,
76
57
}
77
58
78
- func (bot * Bot ) send (msg interface {}) error {
79
- data , err := bot .marshal (msg )
80
- if err != nil {
81
- return err
82
- }
83
-
59
+ func (bot * Bot ) send (msg interface {}) (err error ) {
84
60
var reqBody * bytes.Buffer
85
61
if bot .threadSafe {
86
- reqBody = bytes .NewBuffer (data )
62
+ reqBody = bytes .NewBuffer (nil )
87
63
} else {
88
64
reqBody = bot .reqbuf
89
- reqBody .Write (data )
90
65
}
91
66
defer reqBody .Reset ()
92
67
68
+ if err = json .NewEncoder (reqBody ).Encode (msg ); err != nil {
69
+ return err
70
+ }
71
+
93
72
var resData resData
94
73
if err = bot .doPost (bot .webhookURL , jsonReqHeader , reqBody , & resData ); err != nil {
95
74
return err
@@ -112,19 +91,7 @@ func (bot *Bot) doPost(url string, reqHeader map[string]string, reqBody io.Reade
112
91
}
113
92
defer res .Body .Close ()
114
93
115
- var resbuf * bytes.Buffer
116
- if bot .threadSafe {
117
- resbuf = new (bytes.Buffer )
118
- } else {
119
- resbuf = bot .resbuf
120
- }
121
- defer resbuf .Reset ()
122
-
123
- if _ , err = io .Copy (resbuf , res .Body ); err != nil { // TODO 优化这次多余的拷贝
124
- return err
125
- }
126
-
127
- return bot .unmarshal (resbuf .Bytes (), resData )
94
+ return json .NewDecoder (res .Body ).Decode (resData )
128
95
}
129
96
130
97
type resData struct {
0 commit comments