| Josh Bleecher Snyder | 78707d6 | 2025-04-30 21:06:49 +0000 | [diff] [blame] | 1 | // Package browser provides functions for opening URLs in a web browser. |
| 2 | package browser |
| 3 | |
| 4 | import ( |
| Josh Bleecher Snyder | d0a3cd6 | 2025-05-03 15:46:45 -0700 | [diff] [blame^] | 5 | "log/slog" |
| Josh Bleecher Snyder | 78707d6 | 2025-04-30 21:06:49 +0000 | [diff] [blame] | 6 | "os/exec" |
| 7 | "runtime" |
| Josh Bleecher Snyder | 11c97f2 | 2025-05-02 16:36:46 -0700 | [diff] [blame] | 8 | "strings" |
| Josh Bleecher Snyder | 78707d6 | 2025-04-30 21:06:49 +0000 | [diff] [blame] | 9 | ) |
| 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 Snyder | e54b00a | 2025-04-30 16:48:02 -0700 | [diff] [blame] | 16 | func Open(url string) { |
| Josh Bleecher Snyder | 11c97f2 | 2025-05-02 16:36:46 -0700 | [diff] [blame] | 17 | if strings.TrimSpace(url) == "" { |
| 18 | return |
| 19 | } |
| Josh Bleecher Snyder | 78707d6 | 2025-04-30 21:06:49 +0000 | [diff] [blame] | 20 | var cmd *exec.Cmd |
| 21 | switch runtime.GOOS { |
| 22 | case "darwin": |
| Josh Bleecher Snyder | e54b00a | 2025-04-30 16:48:02 -0700 | [diff] [blame] | 23 | cmd = exec.Command("open", url) |
| Josh Bleecher Snyder | 78707d6 | 2025-04-30 21:06:49 +0000 | [diff] [blame] | 24 | case "windows": |
| Josh Bleecher Snyder | e54b00a | 2025-04-30 16:48:02 -0700 | [diff] [blame] | 25 | cmd = exec.Command("cmd", "/c", "start", url) |
| Josh Bleecher Snyder | 78707d6 | 2025-04-30 21:06:49 +0000 | [diff] [blame] | 26 | default: // Linux and other Unix-like systems |
| Josh Bleecher Snyder | e54b00a | 2025-04-30 16:48:02 -0700 | [diff] [blame] | 27 | cmd = exec.Command("xdg-open", url) |
| Josh Bleecher Snyder | 78707d6 | 2025-04-30 21:06:49 +0000 | [diff] [blame] | 28 | } |
| 29 | if b, err := cmd.CombinedOutput(); err != nil { |
| Josh Bleecher Snyder | d0a3cd6 | 2025-05-03 15:46:45 -0700 | [diff] [blame^] | 30 | slog.Debug("failed to open browser", "err", err, "url", url, "output", string(b)) |
| Josh Bleecher Snyder | 78707d6 | 2025-04-30 21:06:49 +0000 | [diff] [blame] | 31 | } |
| 32 | } |