-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtab.go
84 lines (73 loc) · 2 KB
/
tab.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
package vBrowser
import (
"io"
"net/http"
"net/url"
)
type Tab struct {
Location *url.URL
PageResponse *http.Response
// Document *goquery.Document
browser *Browser
httpClient *http.Client
ajaxHttpClient *http.Client
BeforeAjax []func(r *http.Request)
AfterAjax []func(r *http.Response)
}
// Load a new page in the tab (without referer)
func (t *Tab) Open(url string) (err error) {
return t.load(url, false)
}
// jump to a page in the tab (with referer)
func (t *Tab) Jump(jumpUrl string) (err error) {
return t.load(jumpUrl, true)
}
func (t *Tab) load(loadUrl string, withReferer bool) error {
if t.PageResponse != nil {
t.PageResponse.Body.Close()
}
location, err := url.Parse(loadUrl)
if err != nil {
return &Error{Op: ParseURL, Err: err}
}
req, err := http.NewRequest(http.MethodGet, loadUrl, nil)
if err != nil {
return &Error{Op: CreateRequest, Err: err}
}
if withReferer {
// log.Println("set Referer", loadUrl)
req.Header.Set("Referer", loadUrl)
}
resp, err := t.httpClient.Do(req)
if err != nil {
return &Error{Op: DoRequest, Err: err}
}
/* doc, err := goquery.NewDocumentFromReader(resp.Body)
if err != nil {
return &Error{Op: ParseDocument, Err: err}
}*/
t.Location = location
t.PageResponse = resp
// t.Document = doc
return nil
}
// request a url (ajax)
func (t *Tab) Request(method, url string, body io.Reader) (page *http.Response, err error) {
req, err := http.NewRequest(method, url, body)
if err != nil {
return nil, &Error{Op: CreateRequest, Err: err}
}
return t.DoAjax(req)
}
// ajax
func (t *Tab) DoAjax(req *http.Request) (page *http.Response, err error) {
if req.URL.Host != t.Location.Host || req.URL.Scheme != t.Location.Scheme {
req.Header.Set("Origin", t.Location.Scheme+"://"+t.Location.Host)
}
req.Header.Set("Referer", t.Location.String())
req.Header.Set("X-requested-with", "XMLHttpRequest")
return t.ajaxHttpClient.Do(req)
}
func (t *Tab) GetPageCookie() []*http.Cookie {
return t.browser.CookieJar.Cookies(t.Location)
}