[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

Run code on Go Playground

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:


References:

[1]
[2]How to cencor certain words written to Stdout and Stderr? : golang