-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresponse.go
89 lines (77 loc) · 1.66 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
package requests
import (
"compress/gzip"
"compress/zlib"
"encoding/json"
"io"
"io/ioutil"
"net/http"
)
type Response struct {
*http.Response
*Request
content []byte
}
// Content return Response Body as []byte
func (resp *Response) Content() (b []byte, err error) {
if resp.content != nil {
return resp.content, nil
}
var reader io.ReadCloser
switch resp.Header.Get("Content-Encoding") {
case "gzip":
if reader, err = gzip.NewReader(resp.Body); err != nil {
return nil, err
}
case "deflate":
if reader, err = zlib.NewReader(resp.Body); err != nil {
return nil, err
}
default:
reader = resp.Body
}
defer reader.Close()
if resp.content, err = ioutil.ReadAll(resp.Body); err != nil {
return nil, err
}
return resp.content, nil
}
// Text return Response Body as string
func (resp *Response) Text() (text string, err error) {
if resp.content == nil {
_, err = resp.Content()
}
text = string(resp.content)
return
}
// Json return Response Body as Json
func (resp *Response) Json(v interface{}) (err error) {
if resp.content == nil {
_, err = resp.Content()
}
return json.Unmarshal(resp.content, v)
}
// Check request success or fail
func (resp *Response) IsOk(code int) bool {
switch code {
case 200, 201, 202:
return true
}
return false
}
func (resp *Response) Cookies() (cookies []*http.Cookie) {
if resp.Client.Jar == nil {
return
}
cookies = resp.Client.Jar.Cookies(resp.Req.URL)
return
}
// Same as Text() func, but toString func ignore error, it is more easy to test
func (resp *Response) ToString() (text string) {
text = Fn(resp.Text)
return
}
func Fn(f func() (string, error)) (res string) {
res, _ = f()
return
}