forked from Gitlink/gitlink-cli
40 lines
1.1 KiB
Go
40 lines
1.1 KiB
Go
package web
|
|
|
|
import (
|
|
"fmt"
|
|
"os/exec"
|
|
"runtime"
|
|
)
|
|
|
|
// platformCommand returns the OS-specific command used to open a URL.
|
|
//
|
|
// Extracted from OpenBrowser so the platform dispatch is unit-testable without
|
|
// actually launching a browser.
|
|
func platformCommand(rawURL string) (name string, args []string) {
|
|
switch runtime.GOOS {
|
|
case "darwin":
|
|
return "open", []string{rawURL}
|
|
case "windows":
|
|
// The empty "" title argument prevents `start` from treating the URL
|
|
// (which may contain "/" or "&") as the console-window title.
|
|
return "cmd", []string{"/c", "start", "", rawURL}
|
|
default:
|
|
return "xdg-open", []string{rawURL}
|
|
}
|
|
}
|
|
|
|
// OpenBrowser opens rawURL in the user's default browser.
|
|
//
|
|
// The command is started detached (cmd.Start, not Run) so the CLI never blocks
|
|
// on the browser process.
|
|
func OpenBrowser(rawURL string) error {
|
|
name, args := platformCommand(rawURL)
|
|
cmd := exec.Command(name, args...)
|
|
if err := cmd.Start(); err != nil {
|
|
return fmt.Errorf("打开浏览器失败: %w", err)
|
|
}
|
|
// Reap the detached process to avoid zombies on Unix.
|
|
go func() { _ = cmd.Wait() }()
|
|
return nil
|
|
}
|