Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I launch a process that is not a file in Go (e.g. open a web page)

Tags:

go

I want to open a web browser:

c, err := exec.Command("http://localhost:4001").Output()
if err != nil {
    fmt.Printf("ERROR: %v, %v\n",err,c)
} else {
    fmt.Printf("OK:%v\n",c)
}

and I get the error

ERROR: exec: "http://localhost:4001": file does not exist

Edit: What I want to achieve is the same as in Windows and C# when you do:

Process.Start("http://localhost:4001")

With it a new instance of your default browser will launch showing the URL

like image 930
Santiago Corredoira Avatar asked Apr 30 '12 00:04

Santiago Corredoira


4 Answers

"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")
}
like image 123
tux21b Avatar answered Oct 19 '22 18:10

tux21b


Under Windows using:

exec.Command("cmd", "/c", "start", "http://localhost:4001/").Start()
like image 39
David Avatar answered Oct 19 '22 17:10

David


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()
like image 3
laslowh Avatar answered Oct 19 '22 19:10

laslowh


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
}
like image 2
Boune Avatar answered Oct 19 '22 19:10

Boune