-
Notifications
You must be signed in to change notification settings - Fork 53
/
response.go
238 lines (194 loc) · 5.71 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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
package gentleman
// Originally based on grequests: https://github.com/levigross/grequests
// Apache License Version 2.0
import (
"bytes"
"encoding/json"
"encoding/xml"
"io"
"io/ioutil"
"net/http"
"os"
"gopkg.in/h2non/gentleman.v2/context"
"gopkg.in/h2non/gentleman.v2/utils"
)
// Response provides a more convenient and higher level Response struct.
// Implements an io.ReadCloser interface.
type Response struct {
// Ok is a boolean flag that validates that the server returned a 2xx code.
Ok bool
// This is the Go error flag – if something went wrong within the request, this flag will be set.
Error error
// Sugar to check if the response status code is a client error (4xx).
ClientError bool
// Sugar to check if the response status code is a server error (5xx).
ServerError bool
// StatusCode is the HTTP Status Code returned by the HTTP Response. Taken from resp.StatusCode.
StatusCode int
// Header stores the response headers as http.Header interface.
Header http.Header
// Cookies stores the parsed response cookies.
Cookies []*http.Cookie
// Expose the native Go http.Response object for convenience.
RawResponse *http.Response
// Expose the native Go http.Request object for convenience.
RawRequest *http.Request
// Expose original request Context for convenience.
Context *context.Context
// Internal buffer store
buffer *bytes.Buffer
}
func buildResponse(ctx *context.Context) (*Response, error) {
resp := ctx.Response
statusRange := int(resp.StatusCode / 100)
res := &Response{
// If your code is within the 2xx range – the response is considered `Ok`
Ok: statusRange >= 2 && statusRange <= 3,
Error: ctx.Error,
ClientError: statusRange == 4,
ServerError: statusRange == 5,
Context: ctx,
RawResponse: resp,
RawRequest: ctx.Request,
StatusCode: resp.StatusCode,
Header: resp.Header,
Cookies: resp.Cookies(),
buffer: bytes.NewBuffer([]byte{}),
}
return res, res.Error
}
// Read is part of our ability to support io.ReadCloser
// if someone wants to make use of the raw body.
func (r *Response) Read(p []byte) (n int, err error) {
if r.Error != nil {
return -1, r.Error
}
return r.RawResponse.Body.Read(p)
}
// Close is part of our ability to support io.ReadCloser if
// someone wants to make use of the raw body.
func (r *Response) Close() error {
io.Copy(ioutil.Discard, r.RawResponse.Body)
if r.Error != nil {
return r.Error
}
return r.RawResponse.Body.Close()
}
// SaveToFile allows you to download the contents
// of the response to a file.
func (r *Response) SaveToFile(fileName string) error {
if r.Error != nil {
return r.Error
}
fd, err := os.Create(fileName)
if err != nil {
return err
}
defer r.Close() // This is a noop if we use the internal ByteBuffer
defer fd.Close()
_, err = io.Copy(fd, r.getInternalReader())
if err != nil && err != io.EOF {
return err
}
return nil
}
// JSON is a method that will populate a struct that is provided `userStruct`
// with the JSON returned within the response body.
func (r *Response) JSON(userStruct interface{}) error {
if r.Error != nil {
return r.Error
}
jsonDecoder := json.NewDecoder(r.getInternalReader())
defer r.Close()
err := jsonDecoder.Decode(&userStruct)
if err != nil && err != io.EOF {
return err
}
return nil
}
// XML is a method that will populate a struct that is provided
// `userStruct` with the XML returned within the response body.
func (r *Response) XML(userStruct interface{}, charsetReader utils.XMLCharDecoder) error {
if r.Error != nil {
return r.Error
}
xmlDecoder := xml.NewDecoder(r.getInternalReader())
if charsetReader != nil {
xmlDecoder.CharsetReader = charsetReader
}
defer r.Close()
if err := xmlDecoder.Decode(&userStruct); err != nil && err != io.EOF {
return err
}
return nil
}
// Bytes returns the response as a byte array.
func (r *Response) Bytes() []byte {
if r.Error != nil {
return nil
}
r.populateResponseByteBuffer()
// Are we still empty?
if r.buffer.Len() == 0 {
return nil
}
return r.buffer.Bytes()
}
// String returns the response as a string.
func (r *Response) String() string {
if r.Error != nil {
return ""
}
r.populateResponseByteBuffer()
return r.buffer.String()
}
// ClearInternalBuffer is a function that will clear the internal buffer that we
// use to hold the .String() and .Bytes() data.
// Once you have used these functions you may want to free up the memory.
func (r *Response) ClearInternalBuffer() {
if r.Error != nil {
return // This is a noop as we will be dereferencing a null pointer
}
r.buffer.Reset()
}
// createResponseBytesBuffer is a utility method that will populate
// the internal byte reader – this is largely used for .String() and .Bytes()
func (r *Response) populateResponseByteBuffer() {
// Have I done this already?
if r.buffer.Len() != 0 {
return
}
defer r.Close()
// Is there any content?
if r.RawResponse.ContentLength == 0 {
return
}
// Did the server tell us how big the response is going to be?
if r.RawResponse.ContentLength > 0 {
r.buffer.Grow(int(r.RawResponse.ContentLength))
}
_, err := io.Copy(r.buffer, r)
if err != nil && err != io.EOF {
r.Error = err
r.RawResponse.Body.Close()
}
}
// getInternalReader because we implement io.ReadCloser and
// optionally hold a large buffer of the response (created by
// the user's request).
func (r *Response) getInternalReader() io.Reader {
if r.buffer.Len() != 0 {
return r.buffer
}
return r
}
// isChunkedResponse iterates over the response's transfer encodings
// and returns either true whether 'chunked' is found, or false, otherwise.
func isChunkedResponse(res *http.Response) bool {
for _, te := range res.TransferEncoding {
if te == "chunked" {
return true
}
}
return false
}