44package browser
55
66import (
7+ "context"
78 "fmt"
89 "io"
910 "os"
@@ -19,16 +20,29 @@ var Stderr io.Writer = os.Stderr
1920
2021// OpenFile opens new browser window for the file path.
2122func OpenFile (path string ) error {
23+ return OpenFileContext (context .Background (), path )
24+ }
25+
26+ // OpenFileContext opens new browser window for the file path.
27+ // Accepts a context.Context to allow for cancelling the operation.
28+ func OpenFileContext (ctx context.Context , path string ) error {
2229 path , err := filepath .Abs (path )
2330 if err != nil {
2431 return err
2532 }
26- return OpenURL ( "file://" + path )
33+ return OpenURLContext ( ctx , "file://" + path )
2734}
2835
2936// OpenReader consumes the contents of r and presents the
3037// results in a new browser window.
3138func OpenReader (r io.Reader ) error {
39+ return OpenReaderContext (context .Background (), r )
40+ }
41+
42+ // OpenReaderContext consumes the contents of r and presents the
43+ // results in a new browser window.
44+ // Accepts a context.Context to allow for cancelling the operation.
45+ func OpenReaderContext (ctx context.Context , r io.Reader ) error {
3246 f , err := os .CreateTemp ("" , "browser.*.html" )
3347 if err != nil {
3448 return fmt .Errorf ("browser: could not create temporary file: %w" , err )
@@ -40,16 +54,25 @@ func OpenReader(r io.Reader) error {
4054 if err := f .Close (); err != nil {
4155 return fmt .Errorf ("browser: caching temporary file failed: %w" , err )
4256 }
43- return OpenFile ( f .Name ())
57+ return OpenFileContext ( ctx , f .Name ())
4458}
4559
4660// OpenURL opens a new browser window pointing to url.
4761func OpenURL (url string ) error {
48- return openBrowser (url )
62+ return OpenURLContext (context .Background (), url )
63+ }
64+
65+ // OpenURLContext opens a new browser window pointing to url.
66+ // Accepts a context.Context to allow for cancelling the operation.
67+ func OpenURLContext (ctx context.Context , url string ) error {
68+ return openBrowser (ctx , url )
4969}
5070
51- func runCmd (prog string , args ... string ) error {
52- cmd := exec .Command (prog , args ... )
71+ func runCmd (ctx context.Context , prog string , args ... string ) error {
72+ if ctx == nil {
73+ ctx = context .Background ()
74+ }
75+ cmd := exec .CommandContext (ctx , prog , args ... )
5376 cmd .Stdout = Stdout
5477 cmd .Stderr = Stderr
5578 return cmd .Run ()
0 commit comments