forked from d1nfinite/zhttp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresponse.go
108 lines (96 loc) · 2.53 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
package zhttp
import (
"io"
"io/ioutil"
"net/http"
"strings"
)
type Response struct {
StatusCode int
Status string
ContentLength int64
RawResponse *http.Response
Error error
}
// String return the body in string type
func (resp *Response) String() string {
data, err := ioutil.ReadAll(resp.RawResponse.Body)
if err != nil {
resp.Error = err
return ""
}
return string(data)
}
// Byte return the body with []byte type
func (resp *Response) Byte() []byte {
data, err := ioutil.ReadAll(resp.RawResponse.Body)
if err != nil {
resp.Error = err
return nil
}
return data
}
// ReadN read and return n byte of body
func (resp *Response) ReadN(n int64) []byte {
body, _ := ioutil.ReadAll(io.LimitReader(resp.RawResponse.Body, n))
return body
}
// Close close the body. Must be called when the response is used
func (resp *Response) Close() error {
return resp.RawResponse.Body.Close()
}
/* RawHeaders return the headers in string type
like this
header1: value1,value11
header2: value2
*/
func (resp *Response) RawHeaders() string {
var rawHeader string
for k, v := range resp.RawResponse.Header {
rawHeader += k + ": " + strings.Join(v, ",") + "\r\n"
}
return strings.TrimSuffix(rawHeader, "\r\n")
}
// HeadersMap return the headers in a map
func (resp *Response) HeadersMap() map[string]string {
headers := map[string]string{}
for k, v := range resp.RawResponse.Header {
headers[k] = strings.Join(v, ",")
}
return headers
}
// GetHeader return a specific header. If header not exist, return empty string and false
func (resp *Response) GetHeader(name string) (string, bool) {
for k, v := range resp.RawResponse.Header {
if k == name {
return strings.Join(v, ","), true
}
}
return "", false
}
// RawCookies return the headers in string type
// like key1=value1; key2=value2
func (resp *Response) RawCookies() string {
var rawCookie string
for _, cookie := range resp.RawResponse.Cookies() {
rawCookie += cookie.Name + "=" + cookie.Value + ";"
}
return strings.TrimSuffix(rawCookie, ";")
}
// CookiesMap return the cookies in a map
func (resp *Response) CookiesMap() map[string]string {
cookies := map[string]string{}
for _, cookie := range resp.RawResponse.Cookies() {
cookies[cookie.Name] = cookie.Value
}
return cookies
}
// GetCookie return a specific cookie. If cookie not exist, return empty string and false
func (resp *Response) GetCookie(name string) (string, bool) {
for _, cookie := range resp.RawResponse.Cookies() {
if cookie.Name == name {
return cookie.Value, true
}
}
return "", false
}