-
Notifications
You must be signed in to change notification settings - Fork 54
/
response.go
256 lines (224 loc) · 4.76 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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
package zhttp
import (
"bufio"
"bytes"
"encoding/json"
"encoding/xml"
"io"
"io/ioutil"
"net/http"
"os"
"strings"
"time"
"github.com/sohaha/zlsgo/zfile"
"github.com/sohaha/zlsgo/zjson"
"golang.org/x/net/html/charset"
)
type Res struct {
err error
r *Engine
req *http.Request
resp *http.Response
client *http.Client
*multipartHelper
downloadProgress DownloadProgress
tmpFile string
requesterBody []byte
responseBody []byte
cost time.Duration
}
func (r *Res) Request() *http.Request {
return r.req
}
func (r *Res) Response() *http.Response {
return r.resp
}
func (r *Res) StatusCode() int {
if r == nil || r.resp == nil {
return 0
}
_, _ = r.ToBytes()
return r.resp.StatusCode
}
func (r *Res) GetCookie() map[string]*http.Cookie {
cookiesRaw := r.Response().Cookies()
cookies := make(map[string]*http.Cookie, len(cookiesRaw))
var cookie *http.Cookie
for i := range cookiesRaw {
if cookie = cookiesRaw[i]; cookie != nil {
cookies[cookie.Name] = cookie
}
}
return cookies
}
func (r *Res) Bytes() []byte {
data, _ := r.ToBytes()
return data
}
func (r *Res) Stream(fn func(line []byte) error) error {
if r.err != nil || r.resp == nil {
return r.err
}
r.responseBody = nil
defer r.resp.Body.Close()
br := bufio.NewReader(r.resp.Body)
for {
bs, err := br.ReadBytes('\n')
if err != nil && err != io.EOF {
return err
}
if err == io.EOF {
break
}
if err = fn(bs); err != nil {
return err
}
}
return nil
}
func (r *Res) ToBytes() ([]byte, error) {
if r.err != nil || r.resp == nil {
return nil, r.err
}
if r.responseBody != nil {
return r.responseBody, nil
}
defer r.resp.Body.Close()
respBody, err := ioutil.ReadAll(r.resp.Body)
_, _ = io.Copy(ioutil.Discard, r.resp.Body)
if err != nil {
r.err = err
return nil, err
}
r.responseBody = forceUTF8(r, respBody)
return r.responseBody, nil
}
func forceUTF8(r *Res, respBody []byte) []byte {
ctype := r.resp.Header.Get("Content-Type")
c, n, _ := charset.DetermineEncoding(respBody, ctype)
if n != "utf-8" && n != "windows-1252" {
b, err := c.NewDecoder().Bytes(respBody)
if err == nil {
return b
}
}
return respBody
}
func (r *Res) Body() (body io.ReadCloser) {
if r.err != nil {
return nil
}
if r.responseBody != nil {
return ioutil.NopCloser(bytes.NewReader(r.responseBody))
}
defer r.resp.Body.Close()
respBody, err := ioutil.ReadAll(r.resp.Body)
_, _ = io.Copy(ioutil.Discard, r.resp.Body)
if err != nil {
r.err = err
return nil
}
r.responseBody = forceUTF8(r, respBody)
return ioutil.NopCloser(bytes.NewReader(r.responseBody))
}
func (r *Res) HTML() (doc QueryHTML) {
data, err := r.ToBytes()
if err != nil {
return QueryHTML{}
}
doc, _ = HTMLParse(data)
return
}
func (r *Res) String() string {
data, _ := r.ToBytes()
return string(data)
}
func (r *Res) JSONs() *zjson.Res {
data, _ := r.ToBytes()
return zjson.ParseBytes(data)
}
func (r *Res) JSON(key string) *zjson.Res {
j := r.JSONs()
return j.Get(key)
}
func (r *Res) ToString() (string, error) {
data, err := r.ToBytes()
return string(data), err
}
func (r *Res) ToJSON(v interface{}) error {
data, err := r.ToBytes()
if err != nil {
return err
}
return json.Unmarshal(data, v)
}
func (r *Res) ToXML(v interface{}) error {
data, err := r.ToBytes()
if err != nil {
return err
}
return xml.Unmarshal(data, v)
}
func (r *Res) ToFile(name string) error {
nameSplit := strings.Split(zfile.RealPath(name), "/")
nameSplitLen := len(nameSplit)
if nameSplitLen > 1 {
dir := strings.Join(nameSplit[0:nameSplitLen-1], "/")
name = zfile.RealPathMkdir(dir) + "/" + nameSplit[nameSplitLen-1]
}
if r.tmpFile != "" {
return zfile.CopyFile(r.tmpFile, name)
}
file, err := os.Create(name)
if err != nil {
return err
}
//noinspection GoUnhandledErrorResult
defer file.Close()
if r.responseBody != nil {
_, err = file.Write(r.responseBody)
return err
}
if r.downloadProgress != nil && r.resp.ContentLength > 0 {
err = r.download(file)
} else {
//noinspection GoUnhandledErrorResult
defer r.resp.Body.Close()
_, err = io.Copy(file, r.resp.Body)
}
if err == nil {
r.tmpFile = name
}
return err
}
func (r *Res) download(file *os.File) error {
var (
current int64
lastTime time.Time
)
p, b := make([]byte, 1024), r.resp.Body
duration, total := 200*time.Millisecond, r.resp.ContentLength
//noinspection GoUnhandledErrorResult
defer b.Close()
for {
l, err := b.Read(p)
if l > 0 {
_, _err := file.Write(p[:l])
if _err != nil {
return _err
}
current += int64(l)
if now := time.Now(); now.Sub(lastTime) > duration {
lastTime = now
r.downloadProgress(current, total)
}
}
if err != nil {
if err == io.EOF {
r.downloadProgress(total, total)
return nil
}
return err
}
}
}