forked from andeya/surfer
/
struct.go
269 lines (220 loc) · 7.53 KB
/
struct.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
package surfer
import (
"bytes"
"crypto/tls"
"fmt"
"io"
"mime/multipart"
"net/http"
"net/http/httputil"
"net/url"
"os"
"strings"
"time"
"github.com/henrylee2cn/surfer/errors"
)
// Attr represents a Download capability.
type Attr int
// AttrMap represents a map of Attr values.
type AttrMap map[Attr]bool
const (
// SendRefererAttr instructs a Download to send the Referer header.
SendReferer Attr = iota
// FollowRedirectsAttr instructs a Download to follow Location headers.
FollowRedirects
)
// Default is the default Download implementation.
type Download struct {
// userAgent is the User-Agent header value sent with requests.
userAgent string
// attrs is the set download attrs.
attrs AttrMap
// cookies stores cookies for every site visited by the browser.
cookies http.CookieJar
//the time of trying to download
tryTimes int
paseTime time.Duration
proxy string
}
// SetTryTimes sets the tryTimes of download.
func (self *Download) SetTryTimes(tryTimes int) {
self.tryTimes = tryTimes
}
// SetPaseTime sets the pase time of retry.
func (self *Download) SetPaseTime(paseTime time.Duration) {
self.paseTime = paseTime
}
// SetCookieJar is used to set the cookie jar the download uses.
func (self *Download) SetCookieJar(cj http.CookieJar) {
self.cookies = cj
}
// SetUserAgent sets the user agent.
func (self *Download) SetUserAgent(userAgent string) {
self.userAgent = userAgent
}
// SetProxy sets a download ProxyHost.
func (self *Download) SetProxy(proxy string) {
self.proxy = proxy
}
// SetAttr sets a download instruction attribute.
func (self *Download) SetAttr(a Attr, v bool) {
self.attrs[a] = v
}
// SetAttrs is used to set all the download attrs.
func (self *Download) SetAttrs(a AttrMap) {
self.attrs = a
}
func (self *Download) Download(method string, u string, ref string, data url.Values, header http.Header, cookies []*http.Cookie) (resp *http.Response, err error) {
switch method {
case "GET":
resp, err = self.Get(u, header, cookies)
case "HEAD":
resp, err = self.Head(u, header, cookies)
case "POST":
resp, err = self.PostForm(u, ref, data, header, cookies)
case "POST-M":
resp, err = self.PostMultipart(u, ref, data, header, cookies)
}
return resp, err
}
// Get requests the given URL using the GET method.
func (self *Download) Get(u string, header http.Header, cookies []*http.Cookie) (*http.Response, error) {
ur, err := url.Parse(u)
if err != nil {
return nil, err
}
client := self.buildClient(ur.Scheme, self.proxy)
return self.httpGET(ur, "", header, cookies, client)
}
// Open requests the given URL using the HEAD method.
func (self *Download) Head(u string, header http.Header, cookies []*http.Cookie) (*http.Response, error) {
ur, err := url.Parse(u)
if err != nil {
return nil, err
}
client := self.buildClient(ur.Scheme, self.proxy)
return self.httpHEAD(ur, "", header, cookies, client)
}
// PostForm requests the given URL using the POST method with the given data.
func (self *Download) PostForm(u string, ref string, data url.Values, header http.Header, cookies []*http.Cookie) (*http.Response, error) {
return self.Post(u, ref, "application/x-www-form-urlencoded", strings.NewReader(data.Encode()), header, cookies)
}
// PostMultipart requests the given URL using the POST method with the given data using multipart/form-data format.
func (self *Download) PostMultipart(u string, ref string, data url.Values, header http.Header, cookies []*http.Cookie) (*http.Response, error) {
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
for k, vs := range data {
for _, v := range vs {
writer.WriteField(k, v)
}
}
err := writer.Close()
if err != nil {
return nil, err
}
return self.Post(u, ref, writer.FormDataContentType(), body, header, cookies)
}
// Post requests the given URL using the POST method.
func (self *Download) Post(u string, ref string, contentType string, body io.Reader, header http.Header, cookies []*http.Cookie) (*http.Response, error) {
ur, err := url.Parse(u)
if err != nil {
return nil, err
}
client := self.buildClient(ur.Scheme, self.proxy)
return self.httpPOST(ur, ref, contentType, body, header, cookies, client)
}
// -- Unexported methods --
// httpGET makes an HTTP GET request for the given URL.
// When via is not nil, and AttributeSendReferer is true, the Referer header will
// be set to ref.
func (self *Download) httpGET(u *url.URL, ref string, header http.Header, cookies []*http.Cookie, client *http.Client) (*http.Response, error) {
req, err := self.buildRequest("GET", u.String(), ref, nil, header, cookies)
if err != nil {
return nil, err
}
return self.httpRequest(req, client)
}
// httpHEAD makes an HTTP HEAD request for the given URL.
// When via is not nil, and AttributeSendReferer is true, the Referer header will
// be set to ref.
func (self *Download) httpHEAD(u *url.URL, ref string, header http.Header, cookies []*http.Cookie, client *http.Client) (*http.Response, error) {
req, err := self.buildRequest("HEAD", u.String(), ref, nil, header, cookies)
if err != nil {
return nil, err
}
return self.httpRequest(req, client)
}
// httpPOST makes an HTTP POST request for the given URL.
// When via is not nil, and AttributeSendReferer is true, the Referer header will
// be set to ref.
func (self *Download) httpPOST(u *url.URL, ref string, contentType string, body io.Reader, header http.Header, cookies []*http.Cookie, client *http.Client) (*http.Response, error) {
req, err := self.buildRequest("POST", u.String(), ref, body, header, cookies)
if err != nil {
return nil, err
}
req.Header.Add("Content-Type", contentType)
return self.httpRequest(req, client)
}
// send uses the given *http.Request to make an HTTP request.
func (self *Download) httpRequest(req *http.Request, client *http.Client) (resp *http.Response, err error) {
for i := 0; i < self.tryTimes; i++ {
resp, err = client.Do(req)
if err != nil {
time.Sleep(self.paseTime)
continue
}
break
}
return
}
// buildClient creates, configures, and returns a *http.Client type.
func (self *Download) buildClient(scheme string, proxy string) *http.Client {
client := &http.Client{}
client.Jar = self.cookies
client.CheckRedirect = self.shouldRedirect
transport := &http.Transport{}
if proxy != "" {
if px, err := url.Parse(proxy); err == nil {
transport.Proxy = http.ProxyURL(px)
}
}
if strings.ToLower(scheme) == "https" {
transport.TLSClientConfig = &tls.Config{RootCAs: nil, InsecureSkipVerify: true}
transport.DisableCompression = true
}
client.Transport = transport
return client
}
// buildRequest creates and returns a *http.Request type.
// Sets any headers that need to be sent with the request.
func (self *Download) buildRequest(method, url string, ref string, body io.Reader, header http.Header, cookies []*http.Cookie) (*http.Request, error) {
req, err := http.NewRequest(method, url, body)
if err != nil {
return nil, err
}
for k, v := range header {
for _, vv := range v {
req.Header.Add(k, vv)
}
}
req.Header.Set("User-Agent", self.userAgent)
if self.attrs[SendReferer] {
req.Header.Set("Referer", ref)
}
for _, cookie := range cookies {
req.AddCookie(cookie)
}
if os.Getenv("SURF_DEBUG_HEADERS") != "" {
d, _ := httputil.DumpRequest(req, false)
fmt.Fprintln(os.Stderr, "===== [DUMP] =====\n", string(d))
}
return req, nil
}
// shouldRedirect is used as the value to http.Client.CheckRedirect.
func (self *Download) shouldRedirect(req *http.Request, _ []*http.Request) error {
if self.attrs[FollowRedirects] {
return nil
}
return errors.NewLocation(
"Redirects are disabled. Cannot follow '%s'.", req.URL.String())
}