The best way to get a string from a Writer

If your function accepts an io.Writer, you can pass a *bytes.Buffer to capture the output.

// import "bytes"
buf := new(bytes.Buffer)
f(buf)
buf.String() // returns a string of what was written to it

If it requires an http.ResponseWriter, you can use a *httptest.ResponseRecorder. A response recorder holds all information that can be sent to a ResponseWriter, but the body is just a *bytes.Buffer.

// import "net/http/httptest"
r := httptest.NewRecorder()
f(r)
r.Body.String() // r.Body is a *bytes.Buffer

Tags:

Io

Go