Refactor network to a top-level module

This commit is contained in:
9seconds
2021-03-14 21:43:30 +03:00
parent 37a78bd1c3
commit f8ad90c845
25 changed files with 231 additions and 192 deletions
+42
View File
@@ -0,0 +1,42 @@
package testlib
import (
"bytes"
"io"
"os"
"strings"
)
func CaptureStdout(callback func()) string {
return captureOutput(&os.Stdout, callback)
}
func CaptureStderr(callback func()) string {
return captureOutput(&os.Stderr, callback)
}
func captureOutput(filefp **os.File, callback func()) string {
oldFp := *filefp
defer func() {
*filefp = oldFp
}()
reader, writer, _ := os.Pipe()
buf := &bytes.Buffer{}
closeChan := make(chan bool)
go func() {
io.Copy(buf, reader) // nolint: errcheck
close(closeChan)
}()
*filefp = writer
callback()
writer.Close()
<-closeChan
return strings.TrimSpace(buf.String())
}