Last active
May 17, 2024 02:08
-
-
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/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Any reason not to use
defer c.bufpool.Put(buf)
right after declaringbuf
?