Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a writer for a String in Go

Tags:

go

I need to use the *template.Execute method but I want the result as a string or byte[] so that I can pass it to another *template.Execute but the method writes its results to a writer. Is there a way to create a writer that will write to a variable I define?

like image 447
NecroTheif Avatar asked Nov 18 '15 01:11

NecroTheif


People also ask

How are string represented in Go?

Go supports two styles of string literals, the double-quote style (or interpreted literals) and the back-quote style (or raw string literals). The zero values of string types are blank strings, which can be represented with "" or `` in literal. Strings can be concatenated with + and += operators.

What is io writer in Golang?

The io.Writer interface is used by many packages in the Go standard library and it represents the ability to write a byte slice into a stream of data. More generically allows you to write data into something that implements the io.Writer interface.

What is Golang string builder?

Builder is used to efficiently append strings using write methods. It offers a subset of the bytes. Buffer methods that allows it to safely avoid extra copying when converting a builder to a string.


2 Answers

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().

like image 56
Tim Cooper Avatar answered Oct 18 '22 10:10

Tim Cooper


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

like image 32
Zombo Avatar answered Oct 18 '22 08:10

Zombo