-
Notifications
You must be signed in to change notification settings - Fork 58
/
response.go
124 lines (100 loc) · 2.22 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
package goz
import (
"net"
"net/http"
"strings"
"github.com/tidwall/gjson"
)
// Response response object
type Response struct {
resp *http.Response
req *http.Request
body []byte
err error
}
// ResponseBody response body
type ResponseBody []byte
// String fmt outout
func (r ResponseBody) String() string {
return string(r)
}
// Read get slice of response body
func (r ResponseBody) Read(length int) []byte {
if length > len(r) {
length = len(r)
}
return r[:length]
}
// GetContents format response body as string
func (r ResponseBody) GetContents() string {
return string(r)
}
// GetRequest get request object
func (r *Response) GetRequest() *http.Request {
return r.req
}
// GetBody parse response body
func (r *Response) GetBody() (ResponseBody, error) {
return ResponseBody(r.body), r.err
}
// GetParsedBody parse response body with gjson
func (r *Response) GetParsedBody() (*gjson.Result, error) {
pb := gjson.ParseBytes(r.body)
return &pb, nil
}
// GetStatusCode get response status code
func (r *Response) GetStatusCode() int {
return r.resp.StatusCode
}
// GetReasonPhrase get response reason phrase
func (r *Response) GetReasonPhrase() string {
status := r.resp.Status
arr := strings.Split(status, " ")
return arr[1]
}
// IsTimeout get if request is timeout
func (r *Response) IsTimeout() bool {
if r.err == nil {
return false
}
netErr, ok := r.err.(net.Error)
if !ok {
return false
}
if netErr.Timeout() {
return true
}
return false
}
// GetHeaders get response headers
func (r *Response) GetHeaders() map[string][]string {
return r.resp.Header
}
// GetHeader get response header
func (r *Response) GetHeader(name string) []string {
headers := r.GetHeaders()
for k, v := range headers {
if strings.ToLower(name) == strings.ToLower(k) {
return v
}
}
return nil
}
// GetHeaderLine get a single response header
func (r *Response) GetHeaderLine(name string) string {
header := r.GetHeader(name)
if len(header) > 0 {
return header[0]
}
return ""
}
// HasHeader get if header exsits in response headers
func (r *Response) HasHeader(name string) bool {
headers := r.GetHeaders()
for k := range headers {
if strings.ToLower(name) == strings.ToLower(k) {
return true
}
}
return false
}