-
-
Notifications
You must be signed in to change notification settings - Fork 19
/
response.go
118 lines (96 loc) · 2.43 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
package rek
import (
"bytes"
"io"
"net/http"
)
// A struct containing the relevant response information returned by a rek request.
type Response struct {
statusCode int
headers map[string]string
encoding []string
cookies []*http.Cookie
res *http.Response
body io.ReadCloser
}
func buildResponse(res *http.Response) (*Response, error) {
resp := &Response{
statusCode: res.StatusCode,
res: res,
}
if res.Header != nil {
headers := make(map[string]string)
for k, v := range res.Header {
headers[k] = v[0]
}
resp.headers = headers
}
if res.Body != nil {
resp.body = res.Body
}
if res.TransferEncoding != nil {
resp.encoding = res.TransferEncoding
}
if res.Cookies() != nil {
resp.cookies = res.Cookies()
}
return resp, nil
}
// The status code of the response (200, 404, etc.).
func (r *Response) StatusCode() int {
return r.statusCode
}
// The response body as a io.ReadCloser. Bear in mind that the response body can only be read once.
func (r *Response) Body() io.ReadCloser {
return r.body
}
// The response body as a byte slice. Bear in mind that the response body can only be read once.
func BodyAsBytes(r io.ReadCloser) ([]byte, error) {
return bodyBytes(r)
}
// The response body as a string. Bear in mind that the response body can only be read once.
func BodyAsString(r io.ReadCloser) (string, error) {
bs, err := bodyBytes(r)
if err != nil {
return "", err
}
return string(bs), nil
}
func bodyBytes(r io.ReadCloser) ([]byte, error) {
buf := bytes.Buffer{}
if _, err := buf.ReadFrom(r); err != nil {
return nil, err
}
if err := r.Close(); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
// The headers associated with the response.
func (r *Response) Headers() map[string]string {
return r.headers
}
// The response's encoding.
func (r *Response) Encoding() []string {
return r.encoding
}
// The Content-Type header for the request (if any).
func (r *Response) ContentType() string {
return r.Headers()["Content-Type"]
}
// The raw *http.Response returned by the operation.
func (r *Response) Raw() *http.Response {
return r.res
}
// The cookies associated with the response.
func (r *Response) Cookies() []*http.Cookie {
return r.cookies
}
// The content length of the response body.
func (r *Response) ContentLength() int64 {
return r.res.ContentLength
}
// The response's status, e.g. "200 OK."
func (r *Response) Status() string {
return r.res.Status
}