Skip to content

Instantly share code, notes, and snippets.

@elithrar
Last active October 16, 2018 15:31
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save elithrar/fbf3772e6a0a6f997d8a to your computer and use it in GitHub Desktop.
Save elithrar/fbf3772e6a0a6f997d8a to your computer and use it in GitHub Desktop.
renderTemplate — write to a buffer first — http://elithrar.github.io/article/custom-handlers-avoiding-globals/
import (
"fmt"
"html/template"
"net/http"
"github.com/oxtoacart/bpool"
)
var bufpool *bpool.BufferPool
// renderTemplate is a wrapper around template.ExecuteTemplate.
// It writes into a bytes.Buffer before writing to the http.ResponseWriter to catch
// any errors resulting from populating the template.
func (c *appContext) renderTemplate(w http.ResponseWriter, name string, data map[string]interface{}) error {
// Ensure the template exists in the map.
tmpl, ok := c.templates[name]
if !ok {
return fmt.Errorf("The template %s does not exist.", name)
}
// Create a buffer to temporarily write to and check if any errors were encountered.
buf := c.bufpool.Get()
err := tmpl.ExecuteTemplate(&buf, "base", data)
if err != nil {
c.bufpool.Put(buf)
return err
}
// Set the header and write the buffer to the http.ResponseWriter
w.Header().Set("Content-Type", "text/html; charset=utf-8")
buf.WriteTo(w)
c.bufpool.Put(buf)
return nil
}
@tp
Copy link

tp commented Jul 18, 2014

Any reason not to use defer c.bufpool.Put(buf) right after declaring buf?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment