Say I have a html/template
like the following:
<html>
<body>
<p>{{SomeFunc .SomeData}}</p>
</body>
and sometimes SomeFunc
returns an error. Is there an idiomatic way to deal with this?
If I write directly to the ResponseWriter
, then a status code 200 has already been written before I encounter the error.
var tmpl *template.Template
func Handler(w http.ResponseWriter, r *http.Request) {
err := tmpl.Execute(w, data)
// "<html><body><p>" has already been written...
// what to do with err?
}
Preferably I would return a status code 400 or some such, but I can't see a way to do this if I use template.Execute
directly on the ResponseWriter
. Is there something I'm missing?
sync.Pool
or another construct—is a slightly more performant way to solve this. Allocate a pool, Get a buffer, write to it and then to the response (on nil error) and then Put the buffer back into the pool. Otherwise you're on point! – Dunston