blob: 387dad3d5690190e54f1cbbcc074a32910297bb9 [file] [log] [blame]
Josh Bleecher Snyder78707d62025-04-30 21:06:49 +00001// Package browser provides functions for opening URLs in a web browser.
2package browser
3
4import (
Josh Bleecher Snyderd0a3cd62025-05-03 15:46:45 -07005 "log/slog"
Josh Bleecher Snyder78707d62025-04-30 21:06:49 +00006 "os/exec"
7 "runtime"
Josh Bleecher Snyder11c97f22025-05-02 16:36:46 -07008 "strings"
Josh Bleecher Snyder78707d62025-04-30 21:06:49 +00009)
10
11// Open opens the specified URL in the system's default browser.
12// It detects the OS and uses the appropriate command:
13// - 'open' for macOS
14// - 'cmd /c start' for Windows
15// - 'xdg-open' for Linux and other Unix-like systems
Josh Bleecher Snydere54b00a2025-04-30 16:48:02 -070016func Open(url string) {
Josh Bleecher Snyder11c97f22025-05-02 16:36:46 -070017 if strings.TrimSpace(url) == "" {
18 return
19 }
Josh Bleecher Snyder78707d62025-04-30 21:06:49 +000020 var cmd *exec.Cmd
21 switch runtime.GOOS {
22 case "darwin":
Josh Bleecher Snydere54b00a2025-04-30 16:48:02 -070023 cmd = exec.Command("open", url)
Josh Bleecher Snyder78707d62025-04-30 21:06:49 +000024 case "windows":
Josh Bleecher Snydere54b00a2025-04-30 16:48:02 -070025 cmd = exec.Command("cmd", "/c", "start", url)
Josh Bleecher Snyder78707d62025-04-30 21:06:49 +000026 default: // Linux and other Unix-like systems
Josh Bleecher Snydere54b00a2025-04-30 16:48:02 -070027 cmd = exec.Command("xdg-open", url)
Josh Bleecher Snyder78707d62025-04-30 21:06:49 +000028 }
29 if b, err := cmd.CombinedOutput(); err != nil {
Josh Bleecher Snyderd0a3cd62025-05-03 15:46:45 -070030 slog.Debug("failed to open browser", "err", err, "url", url, "output", string(b))
Josh Bleecher Snyder78707d62025-04-30 21:06:49 +000031 }
32}