From ce25c090f57cb787956e190e903cea1fcb5549a4 Mon Sep 17 00:00:00 2001 From: Simon Ding Date: Sun, 29 Sep 2024 13:55:16 +0800 Subject: [PATCH] feat: open url at startup --- cmd/main.go | 9 +++++++++ pkg/utils/utils.go | 43 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+) diff --git a/cmd/main.go b/cmd/main.go index 9ce1381..c296094 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -3,8 +3,10 @@ package main import ( "polaris/db" "polaris/log" + "polaris/pkg/utils" "polaris/server" "syscall" + "time" ) func main() { @@ -17,6 +19,13 @@ func main() { log.Panicf("init db error: %v", err) } + go func() { + time.Sleep(2 * time.Second) + if err := utils.OpenURL("http://127.0.0.1:8080"); err != nil { + log.Errorf("open url error: %v", err) + } + + }() s := server.NewServer(dbClient) if err := s.Serve(); err != nil { log.Errorf("server start error: %v", err) diff --git a/pkg/utils/utils.go b/pkg/utils/utils.go index 9bc682d..4125592 100644 --- a/pkg/utils/utils.go +++ b/pkg/utils/utils.go @@ -3,7 +3,9 @@ package utils import ( "encoding/json" "os" + "os/exec" "regexp" + "runtime" "strconv" "strings" "unicode" @@ -183,3 +185,44 @@ func trimMapStringInterface(data interface{}) interface{} { } return data } + +// 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") +}