forked from chanxuehong/wechat
-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.go
214 lines (191 loc) · 5.98 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
package core
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"net/url"
"reflect"
"github.com/bububa/wechat/internal/debug/api"
"github.com/bububa/wechat/internal/debug/api/retry"
"github.com/bububa/wechat/util"
)
type Client struct {
AccessTokenServer
HttpClient *http.Client
}
// NewClient 创建一个新的 Client.
//
// 如果 clt == nil 则默认用 util.DefaultHttpClient
func NewClient(srv AccessTokenServer, clt *http.Client) *Client {
if srv == nil {
panic("nil AccessTokenServer")
}
if clt == nil {
clt = util.DefaultHttpClient
}
return &Client{
AccessTokenServer: srv,
HttpClient: clt,
}
}
func NewClientWithToken(token string, clt *http.Client) *Client {
tokenServer := NewSimpleAccessTokenServer(token, clt)
return NewClient(tokenServer, clt)
}
// GetJSON HTTP GET 微信资源, 然后将微信服务器返回的 JSON 用 encoding/json 解析到 response.
//
// NOTE:
// 1. 一般不需要调用这个方法, 请直接调用高层次的封装函数;
// 2. 最终的 URL == incompleteURL + access_token;
// 3. response 格式有要求, 要么是 *Error, 要么是下面结构体的指针(注意 Error 必须是第一个 Field):
// struct {
// Error
// ...
// }
func (clt *Client) GetJSON(incompleteURL string, response interface{}) (err error) {
ErrorStructValue, ErrorErrCodeValue := checkResponse(response)
httpClient := clt.HttpClient
if httpClient == nil {
httpClient = util.DefaultHttpClient
}
token, err := clt.Token()
if err != nil {
return
}
hasRetried := false
RETRY:
finalURL := incompleteURL + url.QueryEscape(token)
if err = httpGetJSON(httpClient, finalURL, response, clt.Debug()); err != nil {
return
}
switch errCode := ErrorErrCodeValue.Int(); errCode {
case ErrCodeOK:
return
case ErrCodeInvalidCredential, ErrCodeAccessTokenExpired:
errMsg := ErrorStructValue.Field(errorErrMsgIndex).String()
retry.DebugPrintError(errCode, errMsg, token, clt.Debug())
if !hasRetried {
hasRetried = true
ErrorStructValue.Set(errorZeroValue)
if token, err = clt.RefreshToken(token); err != nil {
return
}
retry.DebugPrintNewToken(token, clt.Debug())
goto RETRY
}
retry.DebugPrintFallthrough(token, clt.Debug())
fallthrough
default:
return
}
}
func httpGetJSON(clt *http.Client, url string, response interface{}, debug bool) error {
api.DebugPrintGetRequest(url, debug)
httpResp, err := clt.Get(url)
if err != nil {
return err
}
defer httpResp.Body.Close()
if httpResp.StatusCode != http.StatusOK {
return fmt.Errorf("http.Status: %s", httpResp.Status)
}
return api.DecodeJSONHttpResponse(httpResp.Body, response, debug)
}
// PostJSON 用 encoding/json 把 request marshal 为 JSON, HTTP POST 到微信服务器,
// 然后将微信服务器返回的 JSON 用 encoding/json 解析到 response.
//
// NOTE:
// 1. 一般不需要调用这个方法, 请直接调用高层次的封装函数;
// 2. 最终的 URL == incompleteURL + access_token;
// 3. response 格式有要求, 要么是 *Error, 要么是下面结构体的指针(注意 Error 必须是第一个 Field):
// struct {
// Error
// ...
// }
func (clt *Client) PostJSON(incompleteURL string, request interface{}, response interface{}) (err error) {
ErrorStructValue, ErrorErrCodeValue := checkResponse(response)
buffer := textBufferPool.Get().(*bytes.Buffer)
buffer.Reset()
defer textBufferPool.Put(buffer)
encoder := json.NewEncoder(buffer)
encoder.SetEscapeHTML(false)
if err = encoder.Encode(request); err != nil {
return
}
requestBodyBytes := buffer.Bytes()
if i := len(requestBodyBytes) - 1; i >= 0 && requestBodyBytes[i] == '\n' {
requestBodyBytes = requestBodyBytes[:i] // 去掉最后的 '\n', 这样能统一log格式, 不然可能多一个空白行
}
httpClient := clt.HttpClient
if httpClient == nil {
httpClient = util.DefaultHttpClient
}
token, err := clt.Token()
if err != nil {
return
}
hasRetried := false
RETRY:
finalURL := incompleteURL + url.QueryEscape(token)
if err = httpPostJSON(httpClient, finalURL, requestBodyBytes, response, clt.Debug()); err != nil {
return
}
switch errCode := ErrorErrCodeValue.Int(); errCode {
case ErrCodeOK:
return
case ErrCodeInvalidCredential, ErrCodeAccessTokenExpired:
errMsg := ErrorStructValue.Field(errorErrMsgIndex).String()
retry.DebugPrintError(errCode, errMsg, token, clt.Debug())
if !hasRetried {
hasRetried = true
ErrorStructValue.Set(errorZeroValue)
if token, err = clt.RefreshToken(token); err != nil {
return
}
retry.DebugPrintNewToken(token, clt.Debug())
goto RETRY
}
retry.DebugPrintFallthrough(token, clt.Debug())
fallthrough
default:
return
}
}
func httpPostJSON(clt *http.Client, url string, body []byte, response interface{}, debug bool) error {
api.DebugPrintPostJSONRequest(url, body, debug)
httpResp, err := clt.Post(url, "application/json; charset=utf-8", bytes.NewReader(body))
if err != nil {
return err
}
defer httpResp.Body.Close()
if httpResp.StatusCode != http.StatusOK {
return fmt.Errorf("http.Status: %s", httpResp.Status)
}
return api.DecodeJSONHttpResponse(httpResp.Body, response, debug)
}
// checkResponse 检查 response 参数是否满足特定的结构要求, 如果不满足要求则会 panic, 否则返回相应的 reflect.Value.
func checkResponse(response interface{}) (ErrorStructValue, ErrorErrCodeValue reflect.Value) {
responseValue := reflect.ValueOf(response)
if responseValue.Kind() != reflect.Ptr {
panic("the type of response is incorrect")
}
responseStructValue := responseValue.Elem()
if responseStructValue.Kind() != reflect.Struct {
panic("the type of response is incorrect")
}
if t := responseStructValue.Type(); t == errorType {
ErrorStructValue = responseStructValue
} else {
if t.NumField() == 0 {
panic("the type of response is incorrect")
}
v := responseStructValue.Field(0)
if v.Type() != errorType {
panic("the type of response is incorrect")
}
ErrorStructValue = v
}
ErrorErrCodeValue = ErrorStructValue.Field(errorErrCodeIndex)
return
}