Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a flag to prevent launching twice. #910

Merged
merged 2 commits into from
Jul 29, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)
}
Loading