/
response.go
115 lines (86 loc) · 1.85 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
package httpx
import (
"encoding/json"
"encoding/xml"
"io"
"io/ioutil"
"net/http"
)
const ResponseBodyAllSize int64 = 0
type HttpResponse struct {
rawurl string
body io.ReadCloser
header http.Header
status string
statuscode int
}
func (resp *HttpResponse) Body() io.ReadCloser {
return resp.body
}
func (resp *HttpResponse) Bytes() ([]byte, error) {
return ioutil.ReadAll(resp.body)
}
func (resp *HttpResponse) String() string {
buf, err := resp.Bytes()
if err != nil {
return ""
}
return string(buf)
}
func (resp *HttpResponse) JSON(object interface{}) error {
buf, err := resp.Bytes()
if err != nil {
return err
}
return json.Unmarshal(buf, object)
}
func (resp *HttpResponse) XML(object interface{}) error {
buf, err := resp.Bytes()
if err != nil {
return err
}
return xml.Unmarshal(buf, object)
}
func (resp *HttpResponse) JSONMapper(data interface{}) error {
dec := json.NewDecoder(resp.body)
for {
if err := dec.Decode(data); err != nil {
if err == io.EOF {
break
}
return err
}
}
return nil
}
func (resp *HttpResponse) XMLMapper(data interface{}) error {
dec := xml.NewDecoder(resp.body)
for {
if err := dec.Decode(data); err != nil {
if err == io.EOF {
break
}
return err
}
}
return nil
}
func (resp *HttpResponse) RawURL() string {
return resp.rawurl
}
func (resp *HttpResponse) Header(key string) string {
return resp.header.Get(key)
}
func (resp *HttpResponse) Headers() http.Header {
return resp.header
}
func (resp *HttpResponse) Status() string {
return resp.status
}
func (resp *HttpResponse) StatusCode() int {
return resp.statuscode
}
func (resp *HttpResponse) Close() error {
io.Copy(ioutil.Discard, resp.body)
return resp.body.Close()
}