How can I launch a process that is not a file in Go (e.g. open a web page)
Under Windows using:
exec.Command("cmd", "/c", "start", "http://localhost:4001/").Start()
Using
exec.Command("open", "http://localhost:4001/").Start()
in tux21b's answer above didn't work for me on Windows. However this did:
exec.Command(`C:\Windows\System32\rundll32.exe`, "url.dll,FileProtocolHandler", "http://localhost:4001/").Start()
"http://localhost:4001/"
is a URL, it can not be executed, but you can execute a web browser (e.g. firefox
) and pass the URL as first argument.
On Windows, OS X, and Linux helper programs exist which can be used to start the default web browser. I guess there is a similar thing for FreeBSD and Android, but I am not sure about it. The following snippet should work on Windows, OS X, and most Linux distros:
var err error
switch runtime.GOOS {
case "linux":
err = exec.Command("xdg-open", "http://localhost:4001/").Start()
case "windows", "darwin":
err = exec.Command("open", "http://localhost:4001/").Start()
default:
err = fmt.Errorf("unsupported platform")
}
https://github.com/golang/go/blob/33ed35647520f2162c2fed1b0e5f19cec2c65de3/src/cmd/internal/browser/browser.go
// Commands returns a list of possible commands to use to open a url.
func Commands() [][]string {
var cmds [][]string
if exe := os.Getenv("BROWSER"); exe != "" {
cmds = append(cmds, []string{exe})
}
switch runtime.GOOS {
case "darwin":
cmds = append(cmds, []string{"/usr/bin/open"})
case "windows":
cmds = append(cmds, []string{"cmd", "/c", "start"})
default:
cmds = append(cmds, []string{"xdg-open"})
}
cmds = append(cmds, []string{"chrome"}, []string{"google-chrome"}, []string{"firefox"})
return cmds
}
// Open tries to open url in a browser and reports whether it succeeded.
func Open(url string) bool {
for _, args := range Commands() {
cmd := exec.Command(args[0], append(args[1:], url)...)
if cmd.Start() == nil {
return true
}
}
return false
}