CaptureUserOut captures output written to UserOut to a string. Capturing starts when it is called. It returns an anonymous function that when called, will return a string containing the output during capture, and revert once again to the original value of UserOut.Out.
()
| 14 | // when called, will return a string containing the output during capture, and |
| 15 | // revert once again to the original value of UserOut.Out. |
| 16 | func CaptureUserOut() func() string { |
| 17 | old := output.UserOut.Out // keep backup of the real stdout |
| 18 | r, w, _ := os.Pipe() |
| 19 | output.UserOut.Out = w |
| 20 | |
| 21 | return func() string { |
| 22 | outC := make(chan string) |
| 23 | // copy the output in a separate goroutine so printing can't block indefinitely |
| 24 | go func() { |
| 25 | var buf bytes.Buffer |
| 26 | _, err := io.Copy(&buf, r) |
| 27 | CheckErr(err) |
| 28 | outC <- buf.String() |
| 29 | }() |
| 30 | |
| 31 | // back to normal state |
| 32 | CheckClose(w) |
| 33 | output.UserOut.Out = old // restoring the real stdout |
| 34 | |
| 35 | out := <-outC |
| 36 | return out |
| 37 | } |
| 38 | } |
| 39 | |
| 40 | // CaptureUserErr captures output written to UserErr to a string. |
| 41 | // Capturing starts when it is called. It returns an anonymous function that |