[Golang] io.Writer to string
Use Buffer in Go bytes package to get string from io.Writer (io Writer). Common pattern as follows:
import "bytes"
var b bytes.Buffer
fn(b)
b.String()
text/template Example
package main
import (
"bytes"
"fmt"
"text/template"
)
type TmplData struct {
Name string
}
var testTmpl = `Hello {{.Name}}`
func main() {
data := TmplData{Name: "World"}
tmpl, err := template.New("test").Parse(testTmpl)
if err != nil {
fmt.Println(err)
}
var b bytes.Buffer
err = tmpl.Execute(&b, &data)
fmt.Println(b.String())
}
Final output:
Hello World
Tested on:
- Ubuntu Linux 16.10
- Go 1.7.5
- Go Playground
References:
[1] |
[2] | How to cencor certain words written to Stdout and Stderr? : golang |