forked from chanxuehong/wechat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
205 lines (183 loc) · 5.63 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
package core
import (
"bytes"
"fmt"
"net/http"
"net/url"
"reflect"
"github.com/chanxuehong/wechat.v2/internal/debug/api"
"github.com/chanxuehong/wechat.v2/internal/debug/api/retry"
"github.com/chanxuehong/wechat.v2/json"
)
type Client struct {
AccessTokenServer
HttpClient *http.Client
}
// NewClient 创建一个新的 Client.
// 如果 clt == nil 则默认用 http.DefaultClient
func NewClient(srv AccessTokenServer, clt *http.Client) *Client {
if srv == nil {
panic("nil AccessTokenServer")
}
if clt == nil {
clt = http.DefaultClient
}
return &Client{
AccessTokenServer: srv,
HttpClient: 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 = http.DefaultClient
}
token, err := clt.Token()
if err != nil {
return
}
hasRetried := false
RETRY:
finalURL := incompleteURL + url.QueryEscape(token)
if err = httpGetJSON(httpClient, finalURL, response); err != nil {
return
}
switch errCode := ErrorErrCodeValue.Int(); errCode {
case ErrCodeOK:
return
case ErrCodeInvalidCredential, ErrCodeAccessTokenExpired:
errMsg := ErrorStructValue.Field(errorErrMsgIndex).String()
retry.DebugPrintError(errCode, errMsg, token)
if !hasRetried {
hasRetried = true
ErrorStructValue.Set(errorZeroValue)
if token, err = clt.RefreshToken(token); err != nil {
return
}
retry.DebugPrintNewToken(token)
goto RETRY
}
retry.DebugPrintFallthrough(token)
fallthrough
default:
return
}
}
func httpGetJSON(clt *http.Client, url string, response interface{}) error {
api.DebugPrintGetRequest(url)
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)
}
// 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)
bodyBuf := textBufferPool.Get().(*bytes.Buffer)
bodyBuf.Reset()
defer textBufferPool.Put(bodyBuf)
if err = json.NewEncoder(bodyBuf).Encode(request); err != nil {
return
}
requestBodyBytes := bodyBuf.Bytes()
if i := len(requestBodyBytes) - 1; i >= 0 && requestBodyBytes[i] == '\n' {
requestBodyBytes = requestBodyBytes[:i] // 去掉最后的 '\n', 这样能统一log格式, 不然可能多一个空白行
}
httpClient := clt.HttpClient
if httpClient == nil {
httpClient = http.DefaultClient
}
token, err := clt.Token()
if err != nil {
return
}
hasRetried := false
RETRY:
finalURL := incompleteURL + url.QueryEscape(token)
if err = httpPostJSON(httpClient, finalURL, requestBodyBytes, response); err != nil {
return
}
switch errCode := ErrorErrCodeValue.Int(); errCode {
case ErrCodeOK:
return
case ErrCodeInvalidCredential, ErrCodeAccessTokenExpired:
errMsg := ErrorStructValue.Field(errorErrMsgIndex).String()
retry.DebugPrintError(errCode, errMsg, token)
if !hasRetried {
hasRetried = true
ErrorStructValue.Set(errorZeroValue)
if token, err = clt.RefreshToken(token); err != nil {
return
}
retry.DebugPrintNewToken(token)
goto RETRY
}
retry.DebugPrintFallthrough(token)
fallthrough
default:
return
}
}
func httpPostJSON(clt *http.Client, url string, body []byte, response interface{}) error {
api.DebugPrintPostJSONRequest(url, body)
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)
}
// 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
}