How to copy os.Stdout output to string variable
问题 I have a function like this: package main import ( "fmt" ) // PrintSomething prints some thing func PrintSomething() { fmt.Println("print something") } func main() { PrintSomething() } How do I wrap PrintSomething to another function call CaptureSomething to save the string "print something" to a variable and return it? 回答1: Create pipe and set stdout to the pipe writer. Start a goroutine to copy the pipe reader to a buffer. When done, close the pipe writer and wait for goroutine to complete