-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcage.go
76 lines (62 loc) · 1.3 KB
/
cage.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package cage
import (
"bytes"
"io"
"os"
"strings"
"time"
)
type container struct {
backupStdout *os.File
writerStdout *os.File
backupStderr *os.File
writerStderr *os.File
data string
channel chan string
Data []string
}
func Start() *container {
rStdout, wStdout, _ := os.Pipe()
rStderr, wStderr, _ := os.Pipe()
c := &container{
backupStdout: os.Stdout,
writerStdout: wStdout,
backupStderr: os.Stderr,
writerStderr: wStderr,
channel: make(chan string),
}
os.Stdout = c.writerStdout
os.Stderr = c.writerStderr
go func(out chan string, readerStdout *os.File, readerStderr *os.File) {
var bufStdout bytes.Buffer
_, _ = io.Copy(&bufStdout, readerStdout)
if bufStdout.Len() > 0 {
out <- bufStdout.String()
}
var bufStderr bytes.Buffer
_, _ = io.Copy(&bufStderr, readerStderr)
if bufStderr.Len() > 0 {
out <- bufStderr.String()
}
}(c.channel, rStdout, rStderr)
go func(c *container) {
for {
select {
case out := <-c.channel:
c.data += out
}
}
}(c)
return c
}
func Stop(c *container) {
_ = c.writerStdout.Close()
_ = c.writerStderr.Close()
time.Sleep(10 * time.Millisecond)
os.Stdout = c.backupStdout
os.Stderr = c.backupStderr
c.Data = strings.Split(c.data, "\n")
if c.Data[len(c.Data)-1] == "" {
c.Data = c.Data[:len(c.Data)-1]
}
}