forked from addcnos/youdu
-
Notifications
You must be signed in to change notification settings - Fork 0
/
response.go
69 lines (53 loc) · 1.31 KB
/
response.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
package youdu
import (
"encoding/json"
"io"
)
type Response struct {
ErrCode int `json:"errcode"`
ErrMsg string `json:"errmsg"`
Encrypt string `json:"encrypt,omitempty"`
}
type responseOptions struct {
needDecrypt bool
}
type responseOption func(*responseOptions)
func newResponseOptions(opts ...responseOption) *responseOptions {
args := &responseOptions{}
for _, opt := range opts {
opt(args)
}
return args
}
func withResponseDecrypt() responseOption {
return func(args *responseOptions) {
args.needDecrypt = true
}
}
func (c *Client) decodeResponse(body io.Reader, resp interface{}, opts ...responseOption) error {
opt := newResponseOptions(opts...)
if !opt.needDecrypt {
return json.NewDecoder(body).Decode(resp)
}
return c.decodeResponseWithDecrypt(body, resp, opts...)
}
func (c *Client) decodeResponseWithDecrypt(body io.Reader, resp interface{}, opts ...responseOption) error {
var r Response
if err := json.NewDecoder(body).Decode(&r); err != nil {
return err
}
if r.ErrCode != 0 {
return newError(r.ErrCode, r.ErrMsg)
}
if r.Encrypt == "" {
return newError(-1, "encrypt is empty")
}
rawData, err := c.encryptor.Decrypt(r.Encrypt)
if err != nil {
return err
}
if rawData.Data == nil {
return newError(-1, "data is nil")
}
return json.Unmarshal(rawData.Data, resp)
}