blob: 9b0a89f13ca8b61fdc8e0011638ee621b0b264b4 [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 Snyder78707d62025-04-30 21:06:49 +00005 "fmt"
6 "os"
7 "os/exec"
8 "runtime"
Josh Bleecher Snyder11c97f22025-05-02 16:36:46 -07009 "strings"
Josh Bleecher Snyder78707d62025-04-30 21:06:49 +000010)
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 Snydere54b00a2025-04-30 16:48:02 -070017func Open(url string) {
Josh Bleecher Snyder11c97f22025-05-02 16:36:46 -070018 if strings.TrimSpace(url) == "" {
19 return
20 }
Josh Bleecher Snyder78707d62025-04-30 21:06:49 +000021 var cmd *exec.Cmd
22 switch runtime.GOOS {
23 case "darwin":
Josh Bleecher Snydere54b00a2025-04-30 16:48:02 -070024 cmd = exec.Command("open", url)
Josh Bleecher Snyder78707d62025-04-30 21:06:49 +000025 case "windows":
Josh Bleecher Snydere54b00a2025-04-30 16:48:02 -070026 cmd = exec.Command("cmd", "/c", "start", url)
Josh Bleecher Snyder78707d62025-04-30 21:06:49 +000027 default: // Linux and other Unix-like systems
Josh Bleecher Snydere54b00a2025-04-30 16:48:02 -070028 cmd = exec.Command("xdg-open", url)
Josh Bleecher Snyder78707d62025-04-30 21:06:49 +000029 }
30 if b, err := cmd.CombinedOutput(); err != nil {
31 fmt.Fprintf(os.Stderr, "failed to open browser: %v: %s\n", err, b)
32 }
33}