CaptureOutputToFile captures Stdout 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 os.StdOut.
()
| 93 | // CaptureOutputToFile captures Stdout to a string. Capturing starts when it is called. It returns an anonymous function that when called, will return a string |
| 94 | // containing the output during capture, and revert once again to the original value of os.StdOut. |
| 95 | func CaptureOutputToFile() (func() string, error) { |
| 96 | oldStdout := os.Stdout // keep backup of the real stdout |
| 97 | oldStderr := os.Stderr |
| 98 | f, err := os.CreateTemp("", "CaptureOutputToFile") |
| 99 | if err != nil { |
| 100 | return nil, err |
| 101 | } |
| 102 | os.Stdout = f |
| 103 | os.Stderr = f |
| 104 | |
| 105 | return func() string { |
| 106 | _ = f.Close() |
| 107 | os.Stdout = oldStdout // restoring the real stdout |
| 108 | os.Stderr = oldStderr |
| 109 | out, err := os.ReadFile(f.Name()) |
| 110 | if err != nil { |
| 111 | out = fmt.Appendf(nil, "failed to read file: %v", err) |
| 112 | } |
| 113 | defer func() { |
| 114 | _ = os.RemoveAll(f.Name()) |
| 115 | }() |
| 116 | return string(out) |
| 117 | }, nil |
| 118 | } |
no outgoing calls