-
Notifications
You must be signed in to change notification settings - Fork 0
/
response.go
118 lines (87 loc) · 2.32 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 r
import (
"encoding/json"
"io/ioutil"
"net/http"
)
type Response struct {
StatusCode int // e.g. 200
Status string // e.g. "200 OK"
Proto string // e.g. "HTTP/1.0"
// The Request that was sent to obtain this Response.
// Request's Body is nil (having already been consumed).
// This is only populated for Client requests.
Request *http.Request
// The value is the BaseResponse Body as bytes
Bytes []byte
// The http.Response type, This type is the original type
// That return from the server.
BaseResponse *http.Response
Close bool
// The Final URL location.
Url string
// The response status as boolean type
Ok bool
}
// NewResponse get a http.Response and return a Response type.
func NewResponse(resp *http.Response) (*Response, error) {
r := &Response{
BaseResponse: resp,
StatusCode: resp.StatusCode,
Status: resp.Status,
Proto: resp.Proto,
Request: resp.Request,
Close: resp.Close,
// Return the url as string type.
Url: resp.Request.URL.String(),
// Return the status code as boolean value.
Ok: resp.StatusCode < 400,
}
// Read the body and save it as bytes
err := r.responseBodyToBytes()
if err != nil {
return r, err
}
return r, nil
}
// Convert the request body(io.Reader) to bytes
// Becouse the io.Reader.Close function
func (r *Response) responseBodyToBytes() error {
defer r.BaseResponse.Body.Close()
body, err := ioutil.ReadAll(r.BaseResponse.Body)
if err != nil {
return err
}
// Save the body for future usage
r.Bytes = body
return nil
}
// Get the response body as a string
func (r *Response) Text() string {
return string(r.Bytes)
}
// Get response header value by name
func (r *Response) Headers(key string) string {
return r.BaseResponse.Header.Get(key)
}
// Parses the JSON-encoded data and stores the result in the value pointed to by v.
// Used the json.Unmarshal function.
func (r *Response) Json(v interface{}) error {
err := json.Unmarshal(r.Bytes, v)
if err != nil {
return err
}
return nil
}
// Get the cookie value by cookie name.
// If the cookie doesnt exists return a empty string.
func (r *Response) Cookies(name string) string {
cookies := r.BaseResponse.Cookies()
for _, c := range cookies {
if c.Name == name {
return c.Value
}
}
return ""
}
// TODO add more features to the response