CaptureConsoleOutput borrows from `github.com/zenizh/go-capturer`. This implementation captures both stdout and stderr. Consider adding the go-capturer module if more granularity is needed
(f func())
| 114 | // CaptureConsoleOutput borrows from `github.com/zenizh/go-capturer`. This implementation captures both stdout |
| 115 | // and stderr. Consider adding the go-capturer module if more granularity is needed |
| 116 | func CaptureConsoleOutput(f func()) string { |
| 117 | r, w, err := os.Pipe() |
| 118 | if err != nil { |
| 119 | panic(err) |
| 120 | } |
| 121 | |
| 122 | stdout := os.Stdout |
| 123 | os.Stdout = w |
| 124 | defer func() { |
| 125 | os.Stdout = stdout |
| 126 | }() |
| 127 | |
| 128 | stderr := os.Stderr |
| 129 | os.Stderr = w |
| 130 | defer func() { |
| 131 | os.Stderr = stderr |
| 132 | }() |
| 133 | |
| 134 | f() |
| 135 | _ = w.Close() |
| 136 | |
| 137 | var buf bytes.Buffer |
| 138 | _, err = io.Copy(&buf, r) |
| 139 | if err != nil { |
| 140 | panic(err) |
| 141 | } |
| 142 | |
| 143 | return buf.String() |
| 144 | } |