| 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 | 78707d6 | 2025-04-30 21:06:49 +0000 | [diff] [blame] | 5 | "fmt" |
| 6 | "os" |
| 7 | "os/exec" |
| 8 | "runtime" |
| Josh Bleecher Snyder | 11c97f2 | 2025-05-02 16:36:46 -0700 | [diff] [blame^] | 9 | "strings" |
| Josh Bleecher Snyder | 78707d6 | 2025-04-30 21:06:49 +0000 | [diff] [blame] | 10 | ) |
| 11 | |
| 12 | // Open opens the specified URL in the system's default browser. |
| 13 | // It detects the OS and uses the appropriate command: |
| 14 | // - 'open' for macOS |
| 15 | // - 'cmd /c start' for Windows |
| 16 | // - 'xdg-open' for Linux and other Unix-like systems |
| Josh Bleecher Snyder | e54b00a | 2025-04-30 16:48:02 -0700 | [diff] [blame] | 17 | func Open(url string) { |
| Josh Bleecher Snyder | 11c97f2 | 2025-05-02 16:36:46 -0700 | [diff] [blame^] | 18 | if strings.TrimSpace(url) == "" { |
| 19 | return |
| 20 | } |
| Josh Bleecher Snyder | 78707d6 | 2025-04-30 21:06:49 +0000 | [diff] [blame] | 21 | var cmd *exec.Cmd |
| 22 | switch runtime.GOOS { |
| 23 | case "darwin": |
| Josh Bleecher Snyder | e54b00a | 2025-04-30 16:48:02 -0700 | [diff] [blame] | 24 | cmd = exec.Command("open", url) |
| Josh Bleecher Snyder | 78707d6 | 2025-04-30 21:06:49 +0000 | [diff] [blame] | 25 | case "windows": |
| Josh Bleecher Snyder | e54b00a | 2025-04-30 16:48:02 -0700 | [diff] [blame] | 26 | cmd = exec.Command("cmd", "/c", "start", url) |
| Josh Bleecher Snyder | 78707d6 | 2025-04-30 21:06:49 +0000 | [diff] [blame] | 27 | default: // Linux and other Unix-like systems |
| Josh Bleecher Snyder | e54b00a | 2025-04-30 16:48:02 -0700 | [diff] [blame] | 28 | cmd = exec.Command("xdg-open", url) |
| Josh Bleecher Snyder | 78707d6 | 2025-04-30 21:06:49 +0000 | [diff] [blame] | 29 | } |
| 30 | if b, err := cmd.CombinedOutput(); err != nil { |
| 31 | fmt.Fprintf(os.Stderr, "failed to open browser: %v: %s\n", err, b) |
| 32 | } |
| 33 | } |