Skip to content

Instantly share code, notes, and snippets.

@threeaccents
Created February 25, 2016 18:55
Show Gist options
  • Star 14 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save threeaccents/607f3bc3a57a2ddd9d57 to your computer and use it in GitHub Desktop.
Save threeaccents/607f3bc3a57a2ddd9d57 to your computer and use it in GitHub Desktop.
open chrome browser with golang function
// openBrowser tries to open the URL in a browser,
// and returns whether it succeed in doing so.
func openBrowser(url string) bool {
var args []string
switch runtime.GOOS {
case "darwin":
args = []string{"open"}
case "windows":
args = []string{"cmd", "/c", "start"}
default:
args = []string{"xdg-open"}
}
cmd := exec.Command(args[0], append(args[1:], url)...)
return cmd.Start() == nil
}
@genghisjahn
Copy link

Thanks for this!

@Lercher
Copy link

Lercher commented Jun 16, 2018

Windows 10 fails to open URLs containing ampersands(&) because they are interpreted as a command separator by cmd.exe, they need to be escaped by a caret(^) i.e. strings.Replace(url, "&", "^&", -1) helps in my special case, but I don't know if that's a better approach in general.

@Allianzcortex
Copy link

Allianzcortex commented Dec 27, 2018

@Lercher You can also use explore "url". I have tested explore "https://google.com" and explore "http://127.0.0.1:8080" on my Windows10 laptop.

@selmison
Copy link

Great!!

@carmel
Copy link

carmel commented May 17, 2021

If multiple browsers are installed on the system(chrome, chromium etc.), does it must to specify the browser installation path?

@asmirbelkic
Copy link

strings.Replace(url, "&", "^&", -1)

hi where did u put that please can u provide a snippet ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment