-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathresponse.go
91 lines (78 loc) · 1.53 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package ydapp
import (
"encoding/json"
"errors"
"fmt"
)
const (
StatusOK = 0
)
var (
ErrNoSuchField = errors.New("no such param")
)
type RawMsg struct {
Data []byte
Length int32
AppId string
}
type ApiResponse struct {
ErrCode int32 `json:"errcode"`
ErrMsg string `json:"errmsg"`
param map[string]interface{}
body []byte
}
func NewReponse(bs []byte) (*ApiResponse, error) {
rsp := ApiResponse{
body: bs,
}
err := json.Unmarshal(bs, &rsp.param)
if err != nil {
return nil, err
}
rsp.ErrCode, err = rsp.GetInt32("errcode")
if err != nil {
return nil, err
}
rsp.ErrMsg, err = rsp.GetString("errmsg")
if err != nil {
return nil, err
}
return &rsp, nil
}
func (this *ApiResponse) GetString(key string) (string, error) {
n, ok := this.param[key]
if !ok {
return "", ErrNoSuchField
}
s, ok := n.(string)
if !ok {
return "", errors.New("type assertion to string failed")
}
return s, nil
}
func (this *ApiResponse) GetInt32(key string) (int32, error) {
n, ok := this.param[key]
if !ok {
return 0, ErrNoSuchField
}
nn, ok := n.(float64)
if !ok {
return 0, errors.New("type assertion to float failed")
}
return int32(nn), nil
}
func (this *ApiResponse) Status() string {
return fmt.Sprintf("errcode: %d, errmsg: %s", this.ErrCode, this.ErrMsg)
}
func (this *ApiResponse) StatusOK() bool {
return this.ErrCode == StatusOK
}
func (this *ApiResponse) Error() error {
if this.StatusOK() {
return nil
}
return errors.New(this.Status())
}
func (this *ApiResponse) Body() []byte {
return this.body
}