From 884bf54a000924670c0a0d86f4c10c2278ff2daf Mon Sep 17 00:00:00 2001 From: Teddy Wing Date: Sun, 23 Jun 2019 18:45:47 +0200 Subject: Add support for the BROWSER environment variable Allow user-defined URL-opening commands via the BROWSER environment variable. This enables using a non-default browser, or changing the browser for a single command. For example, on Mac: $ export BROWSER='open -a Firefox' Windows: > setx BROWSER "start iexplore" In UNIX environments, the command is run through `$SHELL -c`, or `/bin/sh` if `$SHELL` is not set. On Windows, it uses `cmd /c`. Ensure that URLs are properly quoted between UNIX and Windows environments in `fmtBrowserCmd()`. --- browser.go | 17 ++++++++++++++++- browser_unix.go | 22 ++++++++++++++++++++++ browser_windows.go | 9 +++++++++ 3 files changed, 47 insertions(+), 1 deletion(-) create mode 100644 browser_unix.go diff --git a/browser.go b/browser.go index 3e59690..7c60821 100644 --- a/browser.go +++ b/browser.go @@ -55,9 +55,24 @@ func OpenURL(url string) error { } func runCmd(prog string, args ...string) error { - cmd := exec.Command(prog, args...) + var cmd *exec.Cmd + + browser := envBrowserCmd() + if browser != "" { + sh, flag := shell() + url := args[len(args)-1] + browserCmd := fmtBrowserCmd(browser, url) + cmd = exec.Command(sh, flag, browserCmd) + } else { + cmd = exec.Command(prog, args...) + } + cmd.Stdout = Stdout cmd.Stderr = Stderr setFlags(cmd) return cmd.Run() } + +func envBrowserCmd() string { + return os.Getenv("BROWSER") +} diff --git a/browser_unix.go b/browser_unix.go new file mode 100644 index 0000000..30d57db --- /dev/null +++ b/browser_unix.go @@ -0,0 +1,22 @@ +// +build !windows + +package browser + +import ( + "fmt" + "os" +) + +func shell() (shell, flag string) { + shell = os.Getenv("SHELL") + + if shell == "" { + shell = "/bin/sh" + } + + return shell, "-c" +} + +func fmtBrowserCmd(browser, url string) string { + return fmt.Sprintf("%s '%s'", browser, url) +} diff --git a/browser_windows.go b/browser_windows.go index a964c7b..0be67a2 100644 --- a/browser_windows.go +++ b/browser_windows.go @@ -1,6 +1,7 @@ package browser import ( + "fmt" "os/exec" "strings" "syscall" @@ -14,3 +15,11 @@ func openBrowser(url string) error { func setFlags(cmd *exec.Cmd) { cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true} } + +func shell() (shell, flag string) { + return "cmd", "/c" +} + +func fmtBrowserCmd(browser, url string) string { + return fmt.Sprintf("%s %s", browser, url) +} -- cgit v1.2.3