-
Notifications
You must be signed in to change notification settings - Fork 0
/
resp.go
312 lines (270 loc) · 6.52 KB
/
resp.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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
package requests
import (
"bytes"
"compress/gzip"
"encoding/json"
"encoding/xml"
"fmt"
"github.com/PuerkitoBio/goquery"
//"github.com/antchfx/htmlquery"
//"golang.org/x/net/html"
//"github.com/saintfish/chardet"
"github.com/pkg/errors"
"github.com/projectdiscovery/retryablehttp-go"
"io"
"io/ioutil"
"net/http"
"net/url"
"os"
"regexp"
"time"
)
// Resp represents a request with it's response
type Resp struct {
r *Req
req *retryablehttp.Request
resp *http.Response
client *retryablehttp.Client
cost time.Duration
*multipartHelper
reqBody []byte
respBody []byte
downloadProgress DownloadProgress
err error // delayed error
}
func (r *Resp) HandleDecompression(bodyOrig []byte) (bodyDec []byte, err error) {
if r.req == nil || r.req.Request == nil {
return bodyOrig, nil
}
/* encodingHeader := strings.TrimSpace(strings.ToLower(r.Request.Header.Get("Accept-Encoding")))
if encodingHeader == "gzip" || encodingHeader == "gzip, deflate"*/
// Accept-Encoding
if r.req.Request.Header.Get("Content-Encoding") == "gzip" || r.req.Request.Header.Get("Accept-Encoding") != "" {
fmt.Println(111)
gzipreader, err := gzip.NewReader(bytes.NewReader(bodyOrig))
if err != nil {
return bodyDec, err
}
defer gzipreader.Close()
bodyDec, err = ioutil.ReadAll(gzipreader)
if err != nil {
return bodyDec, err
}
return bodyDec, nil
}
return bodyOrig, nil
}
// Request returns *http.Request
func (r *Resp) Request() *retryablehttp.Request {
return r.req
}
// Response returns *http.Response
func (r *Resp) Response() *http.Response {
return r.resp
}
// Bytes returns response body as []byte
func (r *Resp) Bytes() []byte {
data, _ := r.ToBytes()
return data
}
func (r *Resp) Content() []byte {
data, _ := r.ToBytes()
return data
}
func (r *Resp) StatusCode() int {
return r.resp.StatusCode
}
func (r *Resp) ContentLength() int64 {
return r.resp.ContentLength
}
func (r *Resp) GetHeaderValue(key string) string {
return r.resp.Header.Get(key)
}
func (r *Resp) Location() (*url.URL, error) {
return r.resp.Location()
}
func (r *Resp) GetCookies() []*http.Cookie {
return r.resp.Cookies()
}
// ToBytes returns response body as []byte,
// return error if error happend when reading
// the response body
func (r *Resp) ToBytes() ([]byte, error) {
if r.err != nil {
return nil, r.err
}
if r.respBody != nil {
return r.respBody, nil
}
defer r.resp.Body.Close()
respBody, err := ioutil.ReadAll(r.resp.Body)
if err != nil {
r.err = err
_, copyErr := io.Copy(ioutil.Discard, r.resp.Body)
if copyErr != nil {
return nil, copyErr
}
return nil, errors.Wrap(err, "could not read http body")
}
respBody, err = r.HandleDecompression(respBody)
if err != nil {
return nil, errors.Wrap(err, "could not decompress http body")
}
r.respBody = respBody
return r.respBody, nil
}
// String returns response body as string
func (r *Resp) String() string {
data, _ := r.ToBytes()
return string(data)
}
// String returns response body as string
func (r *Resp) Text() string {
data, _ := r.ToBytes()
return string(data)
}
func (r *Resp) GetHeader() http.Header {
return r.resp.Header
}
// ToString returns response body as string,
// return error if error happend when reading
// the response body
func (r *Resp) ToString() (string, error) {
data, err := r.ToBytes()
return string(data), err
}
// ToJSON convert json response body to struct or map
func (r *Resp) Json(v interface{}) error {
data, err := r.ToBytes()
if err != nil {
return err
}
return json.Unmarshal(data, v)
}
// ToXML convert xml response body to struct or map
func (r *Resp) Xml(v interface{}) error {
data, err := r.ToBytes()
if err != nil {
return err
}
return xml.Unmarshal(data, v)
}
func (r *Resp) Html() (*goquery.Document, error) {
data, err := r.ToBytes()
if err != nil {
return nil, err
}
return goquery.NewDocumentFromReader(bytes.NewReader(data))
}
// ToFile download the response body to file with optional download callback
func (r *Resp) ToFile(name string) error {
//TODO set name to the suffix of url path if name == ""
file, err := os.Create(name)
if err != nil {
return err
}
defer file.Close()
if r.respBody != nil {
_, err = file.Write(r.respBody)
return err
}
if r.downloadProgress != nil && r.resp.ContentLength > 0 {
return r.download(file)
}
defer r.resp.Body.Close()
_, err = io.Copy(file, r.resp.Body)
return err
}
func (r *Resp) download(file *os.File) error {
p := make([]byte, 1024)
b := r.resp.Body
defer b.Close()
total := r.resp.ContentLength
var current int64
var lastTime time.Time
defer func() {
r.downloadProgress(current, total)
}()
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) > r.r.progressInterval {
lastTime = now
r.downloadProgress(current, total)
}
}
if err != nil {
if err == io.EOF {
return nil
}
return err
}
}
}
var regNewline = regexp.MustCompile(`\n|\r`)
func (r *Resp) autoFormat(s fmt.State) {
req := r.req
if r.r.flag&Lcost != 0 {
fmt.Fprint(s, req.Method, " ", req.URL.String(), " ", r.cost)
} else {
fmt.Fprint(s, req.Method, " ", req.URL.String())
}
// test if it is should be outputed pretty
var pretty bool
var parts []string
addPart := func(part string) {
if part == "" {
return
}
parts = append(parts, part)
if !pretty && regNewline.MatchString(part) {
pretty = true
}
}
if r.r.flag&LreqBody != 0 { // request body
addPart(string(r.reqBody))
}
if r.r.flag&LrespBody != 0 { // response body
addPart(r.String())
}
for _, part := range parts {
if pretty {
fmt.Fprint(s, "\n")
}
fmt.Fprint(s, " ", part)
}
}
func (r *Resp) miniFormat(s fmt.State) {
req := r.req
if r.r.flag&Lcost != 0 {
fmt.Fprint(s, req.Method, " ", req.URL.String(), " ", r.cost)
} else {
fmt.Fprint(s, req.Method, " ", req.URL.String())
}
if r.r.flag&LreqBody != 0 && len(r.reqBody) > 0 { // request body
str := regNewline.ReplaceAllString(string(r.reqBody), " ")
fmt.Fprint(s, " ", str)
}
if r.r.flag&LrespBody != 0 && r.String() != "" { // response body
str := regNewline.ReplaceAllString(r.String(), " ")
fmt.Fprint(s, " ", str)
}
}
// Format fort the response
func (r *Resp) Format(s fmt.State, verb rune) {
if r == nil || r.req == nil {
return
}
if s.Flag('+') { // include header and format pretty.
fmt.Fprint(s, r.Dump())
} else if s.Flag('-') { // keep all informations in one line.
r.miniFormat(s)
} else { // auto
r.autoFormat(s)
}
}