Skip to content

Commit f52b3d5

Browse files
committed
also release files
1 parent 434336b commit f52b3d5

File tree

2 files changed

+14
-5
lines changed

2 files changed

+14
-5
lines changed

cmd/serve/main.go

+2-1
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ func main() {
1515
target := flag.String("t", "", "target url to proxy")
1616
size := flag.Int("s", 2, "size of the pool")
1717
maxWait := flag.Duration("w", 3*time.Second, "max wait time for a page rendering")
18+
autoFree := flag.Duration("f", 10*time.Minute, "auto close each headless browser after the specified time")
1819

1920
var bypassUAs StringsFlag = bartender.DefaultBypassUserAgentNames
2021
flag.Var(&bypassUAs, "u", "bypass the specified user-agent names")
@@ -38,7 +39,7 @@ func main() {
3839
b.BypassUserAgentNames(bypassUAs...)
3940
b.MaxWait(*maxWait)
4041
b.WarmUp()
41-
b.AutoFree()
42+
b.AutoFree(*autoFree)
4243

4344
err := http.ListenAndServe(*port, b)
4445
if err != nil {

service.go

+12-4
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import (
1212
"time"
1313

1414
"github.com/go-rod/rod"
15+
"github.com/go-rod/rod/lib/launcher"
1516
"github.com/go-rod/rod/lib/proto"
1617
"github.com/mileusna/useragent"
1718
)
@@ -78,7 +79,10 @@ func (b *Bartender) getPage() *rod.Page {
7879
}
7980

8081
func (b *Bartender) newPage() *rod.Page {
81-
page := rod.New().MustConnect().MustPage()
82+
l := launcher.New()
83+
go l.Cleanup()
84+
85+
page := rod.New().ControlURL(l.MustLaunch()).MustConnect().MustPage()
8286

8387
if len(b.blockRequests) > 0 {
8488
router := page.HijackRequests()
@@ -106,18 +110,22 @@ func (b *Bartender) WarmUp() {
106110

107111
// AutoFree automatically closes the each headless browser after a period of time.
108112
// It prevent the memory leak of the headless browser.
109-
func (b *Bartender) AutoFree() {
113+
func (b *Bartender) AutoFree(interval time.Duration) {
110114
go func() {
111115
for {
112-
time.Sleep(10 * time.Minute)
116+
time.Sleep(interval)
117+
118+
page := b.getPage()
119+
browser := page.Browser()
113120

114-
err := b.getPage().Browser().Close()
121+
err := browser.Close()
115122
if err != nil {
116123
log.Println("failed to close browser:", err)
117124

118125
continue
119126
}
120127
b.pool.Put(nil)
128+
log.Println("headless browser freed:", page.SessionID)
121129
}
122130
}()
123131
}

0 commit comments

Comments
 (0)