The best way to get a string from a Writer

IoGo

Io Problem Overview


I have a piece of code that returns a web page using the built-in template system. It accepts a ResponseWriter to which the resulting markup is written. I now want to get to the markup as a string and put it in a database in some cases. I factored out a method that accepts a normal Writer instead of a ResponseWriter and am now trying to get to the written content. Aha - a Pipe may be what I need and then I can get the string with ReadString from the bufio library. But it turns out that the PipeReader coming out from the pipe is not compatible with Reader (that I would need for the ReadString method). W00t. Big surprise. So I could just read into byte[]s using the PipeReader but it feels a bit wrong when ReadString is there.

So what would be the best way to do it? Should I stick with the Pipe and read bytes or is there something better that I haven't found in the manual?

Io Solutions


Solution 1 - Io

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

Solution 2 - Io

The below code is possibly the simplest way to convert Writer (or any type) to string

package main

import "fmt"
import "io"
import "reflect"

func main(){
    var temp io.Writer
    output := fmt.Sprint(temp)
    fmt.Println(reflect.TypeOf(output))

}

Output:

string

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionfroderikView Question on Stackoverflow
Solution 1 - IoStephen WeinbergView Answer on Stackoverflow
Solution 2 - IoRjainView Answer on Stackoverflow