feat: open url at startup

This commit is contained in:
Simon Ding
2024-09-29 13:55:16 +08:00
parent 2683c5dbf2
commit ce25c090f5
2 changed files with 52 additions and 0 deletions

View File

@@ -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)

View File

@@ -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")
}