gunk-dev/the-valley

browser.go

sourceb8e46aa6aaccmain's published tip history
1.7 KiB
1package cmd
2
3import (
4 "fmt"
5 "net/url"
6 "os/exec"
7 "runtime"
8)
9
10// browserOpenCmd returns the command name and arguments needed to open rawURL
11// in the system's default browser for the given GOOS. It is pure (no exec) so
12// the OS dispatch can be unit-tested in isolation.
13//
14// rawURL must be an http or https URL. Validating the scheme rejects dangerous
15// schemes (file:, javascript:) and malformed input before it ever reaches a
16// system handler. On Windows we use rundll32 with url.dll,FileProtocolHandler
17// rather than "cmd /c start", which would otherwise run the URL through cmd.exe
18// — exposing it to shell-metacharacter injection (e.g. "&") and mishandling
19// URLs that need quoting.
20func browserOpenCmd(goos, rawURL string) (string, []string, error) {
21 parsed, err := url.Parse(rawURL)
22 if err != nil {
23 return "", nil, fmt.Errorf("invalid URL %q: %w", rawURL, err)
24 }
25 if parsed.Scheme != "http" && parsed.Scheme != "https" {
26 return "", nil, fmt.Errorf("unsupported URL scheme %q", parsed.Scheme)
27 }
28
29 switch goos {
30 case "darwin":
31 return "open", []string{rawURL}, nil
32 case "linux":
33 return "xdg-open", []string{rawURL}, nil
34 case "windows":
35 return "rundll32", []string{"url.dll,FileProtocolHandler", rawURL}, nil
36 default:
37 return "", nil, fmt.Errorf("unsupported OS: %s", goos)
38 }
39}
40
41// openInBrowser launches the system browser pointed at url. It uses Start (not
42// Run/Wait) so it never blocks the caller — the dashboard UI loop must stay
43// responsive while the browser process starts in the background.
44func openInBrowser(url string) error {
45 name, args, err := browserOpenCmd(runtime.GOOS, url)
46 if err != nil {
47 return err
48 }
49 return exec.Command(name, args...).Start()
50}