-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathresponse.go
More file actions
89 lines (78 loc) · 2.43 KB
/
response.go
File metadata and controls
89 lines (78 loc) · 2.43 KB
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
package xhttp
import (
"encoding/json"
"encoding/xml"
"github.com/obity/xhttp/util"
"google.golang.org/protobuf/proto"
)
type Response struct {
body []byte // 响应的数据
err error // 请求过程中的错误
statusCode int // HTTP状态码
}
// StatusCode 返回HTTP状态码,方便调用者检测错误的不同类型
// 如果请求过程中发生错误(如网络错误、JSON序列化失败等),返回0
func (r *Response) StatusCode() int {
return r.statusCode
}
// 从响应中解析JSON
func (r *Response) ParseJSON(result interface{}) error {
if r.err != nil {
return r.err
}
if result == nil {
return util.WrapError("解析失败", nil, "原因", "result 不能为 nil,需传入 JSON结构体")
}
if err := json.Unmarshal(r.body, result); err != nil {
return util.WrapError("JSON解析失败", err, "响应体", string(r.body))
}
return nil
}
// 从响应中解析XML
func (r *Response) ParseXML(result interface{}) error {
if r.err != nil {
return r.err
}
if result == nil {
return util.WrapError("解析失败", nil, "原因", "result 不能为 nil,需传入 XML结构体")
}
if err := xml.Unmarshal(r.body, result); err != nil {
return util.WrapError("XML解析失败", err, "响应体", string(r.body))
}
return nil
}
// ParseProtobuf 解析Protobuf格式响应
// 注意:result必须是proto.Message接口的实现(如生成的pb结构体指针)
func (r *Response) ParseProtobuf(result proto.Message) error {
if r.err != nil {
return util.WrapError("请求失败", r.err)
}
if result == nil {
return util.WrapError("解析失败", nil, "原因", "result 不能为 nil,需传入 proto.Message")
}
// 解析Protobuf(依赖proto.Unmarshal)
if err := proto.Unmarshal(r.body, result); err != nil {
return util.WrapError("Protobuf解析失败", err,
"响应体长度", len(r.body), // Protobuf是二进制,不适合打印原文
)
}
return nil
}
// ParseBytes 将响应体作为二进制数据返回
// 注意:result 必须是 *[]byte 类型(如 &[]byte{})
func (r *Response) ParseBytes() ([]byte, error) {
if r.err != nil {
return nil, r.err
}
return r.body, nil
}
// ParseString 将响应体转换为字符串返回
// 注意:result 必须是 *string 类型
func (r *Response) ParseString() (*string, error) {
if r.err != nil {
return nil, r.err
}
// 将字节转换为UTF-8字符串(二进制安全)
result := string(r.body)
return &result, nil
}