/
response.go
124 lines (101 loc) · 2.27 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
package fastreq
import (
"bufio"
"bytes"
"net/url"
"os"
"path/filepath"
"regexp"
"github.com/PuerkitoBio/goquery"
"github.com/tidwall/gjson"
"github.com/valyala/fasthttp"
)
// Response ...
type Response struct {
*fasthttp.Response
Request *fasthttp.Request
Dom *goquery.Document
}
func NewResponse() *Response {
return &Response{
Response: fasthttp.AcquireResponse(),
}
}
func (r *Response) BodyString() string {
return unsafeB2S(r.Body())
}
func (r *Response) Json(v interface{}) error {
body, err := r.BodyUncompressed()
if err != nil {
return err
}
return jsonUnmarshal(body, v)
}
func (r *Response) JsonGet(path string) gjson.Result {
return gjson.GetBytes(r.Body(), path)
}
func (r *Response) JsonGetMany(path ...string) []gjson.Result {
return gjson.GetManyBytes(r.Body(), path...)
}
func (r *Response) JsonGetPartOf(path string, v interface{}) error {
part := gjson.GetBytes(r.Body(), path)
if part.Raw == "" {
return nil
}
return jsonUnmarshal(unsafeS2B(part.Raw), v)
}
func (r *Response) BuildDom() error {
if r.Dom == nil {
doc, err := goquery.NewDocumentFromReader(bytes.NewReader(r.Body()))
if err != nil {
return err
}
r.Dom = doc
}
return nil
}
func (r *Response) Copy() *Response {
resp := fasthttp.AcquireResponse()
r.CopyTo(resp)
return &Response{Response: resp}
}
func (r *Response) FileName() string {
disposition := r.Header.Peek("Content-Disposition")
if len(disposition) == 0 {
return ""
}
matches := regexp.MustCompile(`filename[^;=\n]*=(['"]*.*?['"]*)$`).FindSubmatch(disposition)
if len(matches) == 0 {
return ""
}
n := regexp.MustCompile(`['"]`).ReplaceAll(matches[1], []byte{})
un, err := url.QueryUnescape(unsafeB2S(n))
if err != nil {
return unsafeB2S(n)
}
return un
}
func (r *Response) SaveToFile(path, filename string) error {
if filename == "" {
filename = r.FileName()
}
file, err := os.OpenFile(filepath.Join(path, filename), os.O_WRONLY|os.O_CREATE, 0664)
if err != nil {
return err
}
defer file.Close()
w := bufio.NewWriter(file)
if err := r.BodyWriteTo(w); err != nil {
return err
}
if err := w.Flush(); err != nil {
return err
}
return nil
}
func (r *Response) Release() {
if r.Request != nil {
fasthttp.ReleaseRequest(r.Request)
}
fasthttp.ReleaseResponse(r.Response)
}