Last active
March 11, 2025 12:00
-
-
Save sevkin/9798d67b2cb9d07cb05f89f14ba682f8 to your computer and use it in GitHub Desktop.
golang open url in default browser
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://stackoverflow.com/questions/39320371/how-start-web-server-to-open-page-in-browser-in-golang | |
// open opens the specified URL in the default browser of the user. | |
func open(url string) error { | |
var cmd string | |
var args []string | |
switch runtime.GOOS { | |
case "windows": | |
cmd = "cmd" | |
args = []string{"/c", "start"} | |
case "darwin": | |
cmd = "open" | |
default: // "linux", "freebsd", "openbsd", "netbsd" | |
cmd = "xdg-open" | |
} | |
args = append(args, url) | |
return exec.Command(cmd, args...).Start() | |
} |
// https://stackoverflow.com/questions/39320371/how-start-web-server-to-open-page-in-browser-in-golang
// openURL opens the specified URL in the default browser of the user.
func openURL(url string) error {
var cmd string
var args []string
switch runtime.GOOS {
case "windows":
cmd = "cmd"
args = []string{"/c", "start"}
case "darwin":
cmd = "open"
args = []string{url}
default: // "linux", "freebsd", "openbsd", "netbsd"
// Check if running under WSL
if isWSL() {
// Use 'cmd.exe /c start' to open the URL in the default Windows browser
cmd = "cmd.exe"
args = []string{"/c", "start", url}
} else {
// Use xdg-open on native Linux environments
cmd = "xdg-open"
args = []string{url}
}
}
if len(args) > 1 {
// args[0] is used for 'start' command argument, to prevent issues with URLs starting with a quote
args = append(args[:1], append([]string{""}, args[1:]...)...)
}
return exec.Command(cmd, args...).Start()
}
// isWSL checks if the Go program is running inside Windows Subsystem for Linux
func isWSL() bool {
releaseData, err := exec.Command("uname", "-r").Output()
if err != nil {
return false
}
return strings.Contains(strings.ToLower(string(releaseData)), "microsoft")
}
👍
I met error on windows. Url with query params was not opened correctly. I hope this source can help anyone Byron/open-rs#67
small fix
case "windows":
cmd = "cmd"
args = []string{"/c", "start" , url} // added missing "url" param
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This works in WSL