-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathmain.go
62 lines (51 loc) · 1.05 KB
/
main.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
54
55
56
57
58
59
60
61
62
package capturer
import (
"bytes"
"io"
"os"
)
// Capturer has flags whether capture stdout/stderr or not.
type Capturer struct {
captureStdout bool
captureStderr bool
}
// CaptureStdout captures stdout.
func CaptureStdout(f func()) string {
capturer := &Capturer{captureStdout: true}
return capturer.capture(f)
}
// CaptureStderr captures stderr.
func CaptureStderr(f func()) string {
capturer := &Capturer{captureStderr: true}
return capturer.capture(f)
}
// CaptureOutput captures stdout and stderr.
func CaptureOutput(f func()) string {
capturer := &Capturer{captureStdout: true, captureStderr: true}
return capturer.capture(f)
}
func (capturer *Capturer) capture(f func()) string {
r, w, err := os.Pipe()
if err != nil {
panic(err)
}
if capturer.captureStdout {
stdout := os.Stdout
os.Stdout = w
defer func() {
os.Stdout = stdout
}()
}
if capturer.captureStderr {
stderr := os.Stderr
os.Stderr = w
defer func() {
os.Stderr = stderr
}()
}
f()
w.Close()
var buf bytes.Buffer
io.Copy(&buf, r)
return buf.String()
}