browser.go 1.4 KB

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