-
Notifications
You must be signed in to change notification settings - Fork 50
/
response.go
128 lines (105 loc) · 1.88 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
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
package HttpRequest
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
)
type Response struct {
time int64
url string
resp *http.Response
body []byte
}
func (r *Response) Response() *http.Response {
if r!=nil{
return r.resp
}
return nil
}
func (r *Response) StatusCode() int {
if r.resp == nil {
return 0
}
return r.resp.StatusCode
}
func (r *Response) Time() string {
if r != nil {
return fmt.Sprintf("%dms", r.time)
}
return "0ms"
}
func (r *Response) Url() string {
if r != nil {
return r.url
}
return ""
}
func (r *Response) Headers() http.Header {
if r != nil {
return r.resp.Header
}
return nil
}
func (r *Response) Cookies() []*http.Cookie {
if r != nil {
return r.resp.Cookies()
}
return []*http.Cookie{}
}
func (r *Response) Body() ([]byte, error) {
if r == nil {
return []byte{}, errors.New("HttpRequest.Response is nil.")
}
defer r.resp.Body.Close()
if len(r.body) > 0 {
return r.body, nil
}
if r.resp == nil || r.resp.Body == nil {
return nil, errors.New("response or body is nil")
}
b, err := ioutil.ReadAll(r.resp.Body)
if err != nil {
return nil, err
}
r.body = b
return b, nil
}
func (r *Response) Content() (string, error) {
b, err := r.Body()
if err != nil {
return "", nil
}
return string(b), nil
}
func (r *Response) Json(v interface{}) error {
return r.Unmarshal(v)
}
func (r *Response) Unmarshal(v interface{}) error {
b, err := r.Body()
if err != nil {
return err
}
if err := json.Unmarshal(b, &v); err != nil {
return err
}
return nil
}
func (r *Response) Close() error {
if r != nil {
return r.resp.Body.Close()
}
return nil
}
func (r *Response) Export() (string, error) {
b, err := r.Body()
if err != nil {
return "", err
}
var i interface{}
if err := json.Unmarshal(b, &i); err != nil {
return "", errors.New("illegal json: " + err.Error())
}
return Export(i), nil
}