| 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 ( |
| 5 | "context" |
| 6 | "fmt" |
| 7 | "os" |
| 8 | "os/exec" |
| 9 | "runtime" |
| 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 |
| 17 | func Open(ctx context.Context, url string) { |
| 18 | var cmd *exec.Cmd |
| 19 | switch runtime.GOOS { |
| 20 | case "darwin": |
| 21 | cmd = exec.CommandContext(ctx, "open", url) |
| 22 | case "windows": |
| 23 | cmd = exec.CommandContext(ctx, "cmd", "/c", "start", url) |
| 24 | default: // Linux and other Unix-like systems |
| 25 | cmd = exec.CommandContext(ctx, "xdg-open", url) |
| 26 | } |
| 27 | if b, err := cmd.CombinedOutput(); err != nil { |
| 28 | fmt.Fprintf(os.Stderr, "failed to open browser: %v: %s\n", err, b) |
| 29 | } |
| 30 | } |