-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
service.go
238 lines (186 loc) · 4.76 KB
/
service.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
// Package bartender is a service to make web crawlers consume webpages easier
package bartender
import (
"context"
"log"
"net/http"
"net/http/httputil"
"net/url"
"strings"
"sync"
"time"
"github.com/go-rod/rod"
"github.com/go-rod/rod/lib/launcher"
"github.com/go-rod/rod/lib/proto"
"github.com/mileusna/useragent"
)
var DefaultBypassUserAgentNames = []string{
useragent.Opera,
useragent.OperaMini,
useragent.OperaTouch,
useragent.Chrome,
useragent.HeadlessChrome,
useragent.Firefox,
useragent.InternetExplorer,
useragent.Safari,
useragent.Edge,
useragent.Vivaldi,
}
type Bartender struct {
addr string
target *url.URL
proxy *httputil.ReverseProxy
bypassList map[string]bool
pool rod.PagePool
blockRequests []string
maxWait time.Duration
}
func New(addr, target string, poolSize int) *Bartender {
u, err := url.Parse(target)
if err != nil {
panic(err)
}
proxy := httputil.NewSingleHostReverseProxy(u)
return &Bartender{
addr: addr,
target: u,
proxy: proxy,
bypassList: strToMap(DefaultBypassUserAgentNames),
pool: rod.NewPagePool(poolSize),
blockRequests: []string{},
maxWait: 3 * time.Second,
}
}
func (b *Bartender) BypassUserAgentNames(list ...string) {
b.bypassList = strToMap(list)
}
func (b *Bartender) BlockRequests(patterns ...string) {
b.blockRequests = patterns
}
// MaxWait sets the max wait time for the headless browser to render the page.
// If the max wait time is reached, bartender will stop waiting for page rendering and
// immediately return the current html.
func (b *Bartender) MaxWait(d time.Duration) {
b.maxWait = d
}
func (b *Bartender) getPage() *rod.Page {
return b.pool.Get(b.newPage)
}
func (b *Bartender) newPage() *rod.Page {
l := launcher.New()
go l.Cleanup()
page := rod.New().ControlURL(l.MustLaunch()).MustConnect().MustPage()
if len(b.blockRequests) > 0 {
router := page.HijackRequests()
for _, pattern := range b.blockRequests {
router.MustAdd(pattern, func(ctx *rod.Hijack) {
ctx.Response.Fail(proto.NetworkErrorReasonBlockedByClient)
})
}
go router.Run()
}
log.Println("headless browser started:", page.SessionID)
return page
}
// WarmUp pre-creates the headless browsers.
func (b *Bartender) WarmUp() {
for i := 0; i < len(b.pool); i++ {
b.pool.Put(b.getPage())
}
}
// AutoFree automatically closes the each headless browser after a period of time.
// It prevent the memory leak of the headless browser.
func (b *Bartender) AutoFree(interval time.Duration) {
go func() {
for {
time.Sleep(interval)
page := b.getPage()
browser := page.Browser()
err := browser.Close()
if err != nil {
log.Println("failed to close browser:", err)
continue
}
b.pool.Put(nil)
log.Println("headless browser freed:", page.SessionID)
}
}()
}
func (b *Bartender) ServeHTTP(w http.ResponseWriter, r *http.Request) {
ua := useragent.Parse(r.Header.Get("User-Agent"))
if r.Method != http.MethodGet || b.bypassList[ua.Name] {
b.proxy.ServeHTTP(w, r)
return
}
if b.RenderPage(w, r) {
return
}
b.proxy.ServeHTTP(w, r)
}
// RenderPage returns true if the page is rendered by the headless browser.
func (b *Bartender) RenderPage(w http.ResponseWriter, r *http.Request) bool {
u := b.getTargetURL(r.URL)
statusCode, resHeader := getHeader(r.Context(), u)
if !htmlContentType(resHeader) {
return false
}
log.Println("headless render:", u)
for k, vs := range resHeader {
if k == "Content-Length" {
continue
}
for _, v := range vs {
w.Header().Add(k, v)
}
}
w.WriteHeader(statusCode)
page := b.getPage()
defer b.pool.Put(page)
page, cancel := page.Context(r.Context()).WithCancel()
once := sync.Once{}
go func() {
time.Sleep(b.maxWait)
once.Do(func() {
log.Println("max wait time reached, return current html:", u)
body, _ := page.HTML()
_, _ = w.Write([]byte(body))
cancel()
})
}()
_ = page.Navigate(u)
_ = page.WaitStable(time.Second)
body, _ := page.HTML()
once.Do(func() {
log.Println("headless render done:", u)
_, _ = w.Write([]byte(body))
})
return true
}
func (b *Bartender) getTargetURL(reqURL *url.URL) string {
u := *reqURL
u.Scheme = b.target.Scheme
u.Host = b.target.Host
return u.String()
}
func getHeader(ctx context.Context, u string) (int, http.Header) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
if err != nil {
panic(err)
}
res, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
_ = res.Body.Close()
return res.StatusCode, res.Header
}
func htmlContentType(h http.Header) bool {
return strings.Contains(h.Get("Content-Type"), "text/html")
}
func strToMap(list []string) map[string]bool {
m := map[string]bool{}
for _, s := range list {
m[s] = true
}
return m
}