-
Notifications
You must be signed in to change notification settings - Fork 95
/
common.go
53 lines (40 loc) · 925 Bytes
/
common.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package examples
import (
"flag"
"io"
"io/ioutil"
"os"
)
// DemoPathFromArgs returns the value of the -demo command line flag.
// Panics if an error occurs.
func DemoPathFromArgs() string {
fl := new(flag.FlagSet)
demPathPtr := fl.String("demo", "", "Demo file `path`")
err := fl.Parse(os.Args[1:])
if err != nil {
panic(err)
}
demPath := *demPathPtr
return demPath
}
func checkError(err error) {
if err != nil {
panic(err)
}
}
// RedirectStdout redirects standard output to dev null.
// Panics if an error occurs.
func RedirectStdout(f func()) {
// Redirect stdout, the resulting image is written to this
old := os.Stdout
r, w, err := os.Pipe()
checkError(err)
os.Stdout = w
// Discard the output in a separate goroutine so writing to stdout can't block indefinitely
go func() {
for err := error(nil); err == nil; _, err = io.Copy(ioutil.Discard, r) {
}
}()
f()
os.Stdout = old
}