1// Package browser provides helpers to open files, readers, and urls in a browser window.
2//
3// The choice of which browser is started is entirely client dependant.
4package browser
5
6import (
7 "fmt"
8 "io"
9 "io/ioutil"
10 "os"
11 "os/exec"
12 "path/filepath"
13)
14
15// Stdout is the io.Writer to which executed commands write standard output.
16var Stdout io.Writer = os.Stdout
17
18// Stderr is the io.Writer to which executed commands write standard error.
19var Stderr io.Writer = os.Stderr
20
21// OpenFile opens new browser window for the file path.
22func OpenFile(path string) error {
23 path, err := filepath.Abs(path)
24 if err != nil {
25 return err
26 }
27 return OpenURL("file://" + path)
28}
29
30// OpenReader consumes the contents of r and presents the
31// results in a new browser window.
32func OpenReader(r io.Reader) error {
33 f, err := ioutil.TempFile("", "browser.*.html")
34 if err != nil {
35 return fmt.Errorf("browser: could not create temporary file: %v", err)
36 }
37 if _, err := io.Copy(f, r); err != nil {
38 f.Close()
39 return fmt.Errorf("browser: caching temporary file failed: %v", err)
40 }
41 if err := f.Close(); err != nil {
42 return fmt.Errorf("browser: caching temporary file failed: %v", err)
43 }
44 return OpenFile(f.Name())
45}
46
47// OpenURL opens a new browser window pointing to url.
48func OpenURL(url string) error {
49 return openBrowser(url)
50}
51
52func runCmd(prog string, args ...string) error {
53 cmd := exec.Command(prog, args...)
54 cmd.Stdout = Stdout
55 cmd.Stderr = Stderr
56 return cmd.Run()
57}