52 lines
1.6 KiB
Go
52 lines
1.6 KiB
Go
package oauth
|
|
|
|
import (
|
|
"fmt"
|
|
"os/exec"
|
|
"runtime"
|
|
)
|
|
|
|
// CommandExecutor is an interface for executing system commands.
|
|
// This allows for dependency injection and mocking in tests.
|
|
type CommandExecutor interface {
|
|
Execute(name string, args ...string) error
|
|
}
|
|
|
|
// realCommandExecutor is the production implementation that actually executes commands.
|
|
type realCommandExecutor struct{}
|
|
|
|
func (e *realCommandExecutor) Execute(name string, args ...string) error {
|
|
return exec.Command(name, args...).Start()
|
|
}
|
|
|
|
// buildBrowserCommand returns the command and arguments needed to open a browser on the given OS.
|
|
// This is a pure function with no side effects, making it easily testable.
|
|
func buildBrowserCommand(goos, url string) (string, []string, error) {
|
|
switch goos {
|
|
case "darwin":
|
|
return "open", []string{url}, nil
|
|
case "linux":
|
|
return "xdg-open", []string{url}, nil
|
|
case "windows":
|
|
return "rundll32", []string{"url.dll,FileProtocolHandler", url}, nil
|
|
default:
|
|
return "", nil, fmt.Errorf("unsupported platform: %s", goos)
|
|
}
|
|
}
|
|
|
|
// openBrowserWithExecutor opens the browser using the provided executor.
|
|
// This allows for dependency injection in tests.
|
|
func openBrowserWithExecutor(goos, url string, executor CommandExecutor) error {
|
|
cmd, args, err := buildBrowserCommand(goos, url)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return executor.Execute(cmd, args...)
|
|
}
|
|
|
|
// OpenBrowser opens the default browser to the given URL.
|
|
// This is the public API that maintains backward compatibility.
|
|
func OpenBrowser(url string) error {
|
|
return openBrowserWithExecutor(runtime.GOOS, url, &realCommandExecutor{})
|
|
}
|