Skip to content

Commit

Permalink
Add a flag to prevent launching twice. (#910)
Browse files Browse the repository at this point in the history
* Add a flag to prevent launching twice.

* fix go version bug
  • Loading branch information
kvii committed Jul 29, 2023
1 parent e4fc5d8 commit 7fae9b3
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 0 deletions.
6 changes: 6 additions & 0 deletions lib/launcher/error.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package launcher

import "errors"

// ErrAlreadyLaunched is an error that indicates the launcher has already been launched.
var ErrAlreadyLaunched = errors.New("already launched")
13 changes: 13 additions & 0 deletions lib/launcher/launcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (
"path/filepath"
"sort"
"strings"
"sync/atomic"

"github.com/go-rod/rod/lib/defaults"
"github.com/go-rod/rod/lib/launcher/flags"
Expand All @@ -39,6 +40,8 @@ type Launcher struct {

managed bool
serviceURL string

isLaunched int32 // zero means not launched
}

// New returns the default arguments to start browser.
Expand Down Expand Up @@ -377,7 +380,13 @@ func (l *Launcher) MustLaunch() string {
// Launch a standalone temp browser instance and returns the debug url.
// bin and profileDir are optional, set them to empty to use the default values.
// If you want to reuse sessions, such as cookies, set the [Launcher.UserDataDir] to the same location.
//
// Please note launcher can only be used once.
func (l *Launcher) Launch() (string, error) {
if l.hasLaunched() {
return "", ErrAlreadyLaunched
}

defer l.ctxCancel()

bin, err := l.getBin()
Expand Down Expand Up @@ -430,6 +439,10 @@ func (l *Launcher) Launch() (string, error) {
return ResolveURL(u)
}

func (l *Launcher) hasLaunched() bool {
return !atomic.CompareAndSwapInt32(&l.isLaunched, 0, 1)
}

func (l *Launcher) setupCmd(cmd *exec.Cmd) {
l.osSetupCmd(cmd)

Expand Down
14 changes: 14 additions & 0 deletions lib/launcher/launcher_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -310,3 +310,17 @@ func TestBrowserDownloadErr(t *testing.T) {
}}
g.Err(b.Download())
}

func TestLaunchMultiTimes(t *testing.T) {
g := setup(t)

// first time launch, success.
l := launcher.New()
u, e := l.Launch()
g.Neq(u, "")
g.E(e)

// second time launch, failed with ErrAlreadyLaunched.
_, e = l.Launch()
g.Eq(e, launcher.ErrAlreadyLaunched)
}

0 comments on commit 7fae9b3

Please sign in to comment.