How to create a writer for a String in Go

Use an instance of bytes.Buffer, which implements io.Writer:

var buff bytes.Buffer
if err := tpl.Execute(&buff, data); err != nil {
    panic(err)
}

You can then get a string result using buff.String(), or a []byte result using buff.Bytes().


You can also use strings.Builder for this purpose:

package main

import (
   "html/template"
   "strings"
)

func main() {
   t, e := template.New("date").Parse("<p>{{ .month }} - {{ .day }}</p>")
   if e != nil {
      panic(e)
   }
   b := new(strings.Builder)
   t.Execute(b, map[string]int{"month": 12, "day": 31})
   println(b.String())
}

https://golang.org/pkg/strings#Builder

Tags:

Go