Render templates via a buffer, not the ResponseWriter (closes #123)
All checks were successful
check / check (push) Successful in 3m48s

executeTemplate ran the template straight into the ResponseWriter, so a
mid-render failure left the already-emitted prefix written and the
response committed: the handler could no longer set a 500 and the
client got a truncated page, typically with a 200. It also let handler
tests pass against the flushed prefix of a page that aborted below the
assertions.

Execute into a bytes.Buffer instead, and set the content type and copy
the buffer out only once rendering has fully succeeded. On failure
nothing has been written, so the 500 still reaches the client.

Add a test that renders a template failing partway through and asserts
both the 500 and that the body carries no part of the aborted page.
Against the previous streaming renderer it fails on both counts (200,
body "PARTIAL PAGE CONTENTInternal server error").
This commit is contained in:
2026-08-12 09:40:50 +00:00
parent d19e33671c
commit 4a91635b2a
3 changed files with 99 additions and 3 deletions

View File

@@ -1,6 +1,19 @@
package handlers
import "net/http"
import (
"html/template"
"net/http"
)
// AddTemplateForTest registers a template under a page name so that
// the handlers_test package can drive the render path with a
// template of its own.
func (s *Handlers) AddTemplateForTest(
pageTemplate string,
tmpl *template.Template,
) {
s.templates[pageTemplate] = tmpl
}
// RenderTemplateForTest exposes renderTemplate for use in the
// handlers_test package.