-
Notifications
You must be signed in to change notification settings - Fork 0
/
response.go
102 lines (89 loc) · 2 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
package requests
import (
"bytes"
"net/http"
"net/http/httputil"
"os"
"sync"
"github.com/golang-io/pkg/encoding/json"
)
// Response wrap std response
type Response struct {
*http.Response
once *sync.Once
body *bytes.Buffer
}
// newResponse newResponse
func newResponse() *Response {
return &Response{
once: new(sync.Once),
body: new(bytes.Buffer),
}
}
func (resp *Response) getBody() error {
var err error
resp.once.Do(func() {
if resp.Response == nil {
return
}
defer resp.Response.Body.Close()
_, err = resp.body.ReadFrom(resp.Response.Body)
})
return err
}
// WarpResponse warp response
func WarpResponse(resp *http.Response) *Response {
resp2 := newResponse()
resp2.Response = resp
return resp2
}
// StdLib return net/http.Response
func (resp *Response) StdLib() *http.Response {
return resp.Response
}
// Text parse parse to string
func (resp *Response) Text() (string, error) {
if err := resp.getBody(); err != nil {
return "", err
}
return resp.body.String(), nil
}
// Download parse response to a file
func (resp *Response) Download(name string) (int, error) {
if err := resp.getBody(); err != nil {
return 0, err
}
f, err := os.OpenFile(name, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0644)
if err != nil {
return 0, err
}
defer f.Close()
return f.Write(resp.body.Bytes())
}
// JSON parse response
func (resp *Response) JSON(v interface{}) error {
if err := resp.getBody(); err != nil {
return err
}
return json.Unmarshal(resp.body.Bytes(), v)
}
// Dump returns the given request in its HTTP/1.x wire representation.
func (resp *Response) Dump() ([]byte, error) {
return httputil.DumpResponse(resp.Response, true)
}
// DumpIndent warp Dump
func (resp *Response) DumpIndent() string {
dump, _ := resp.Dump()
var b bytes.Buffer
for _, line := range bytes.Split(dump, []byte("\n")) {
b.Write([]byte("< "))
b.Write(line)
b.WriteString("\n")
}
return b.String()
}
// Copy deep copy response
func (resp *Response) Copy() *Response {
resp2 := &Response{}
return resp2
}