Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
renderTemplate — write to a buffer first —
import (
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 {
return err
// Set the header and write the buffer to the http.ResponseWriter
w.Header().Set("Content-Type", "text/html; charset=utf-8")
return nil

This comment has been minimized.

Copy link

@tp 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