Skip to content

html/template: Layouts, Caching, Forms, Flash Messages ​

"HTML templates treat data values as plain text which should be encoded so they can be safely embedded in an HTML document. The escaping is contextual, so actions can appear within JavaScript, CSS, and URI contexts." — package documentation of html/template, Go 1.27 source (src/html/template/doc.go)

Summary: html/template turns Go values into HTML that cannot be hijacked by the data: it reads the template as HTML, CSS, JavaScript and URLs, and picks the right encoder for every action. Around that core a server-rendered Go site needs a handful of habits: layouts built from clones of a parsed set, templates embedded and parsed once, output rendered into a buffer before any byte is sent, forms that re-render with errors and redirect after success, a CSRF token in every form, flash messages that survive exactly one redirect, fingerprinted assets, a CSP nonce, and fragments for htmx. Focus: html/template vs text/template, contextual auto-escaping and the ErrorCode list, template.HTML and the other typed strings, ParseFS with embed, define/block/template, layouts and partials, name clashes in one template set, Clone, dev-mode reload, dot and $, pipelines, range/with/if/else with, FuncMap, comparison functions, printf, index, whitespace trimming, nested templates with dict, rendering to a buffer, ParseForm and validation, post/redirect/get, CSRF tokens and http.CrossOriginProtection, flash cookies, pluralization, cache busting, htmx fragments, CSP nonces, templ and gomponents, Laravel Blade. Learning goal: Build a small server-rendered site in which an attacker's string can never become markup, a broken template can never produce half a page, a refresh can never re-submit a form, and an edit in a template shows up in the browser during development and costs nothing per request in production; and read an html/template error and know which rule of the contextual escaper you broke.

This page owns html/template as it is used to build whole pages in net/http handlers. It does not re-teach its neighbours: the template language itself (actions, variables, pipelines in text/template) is introduced in Strings, Runes, fmt Verbs, text/template & regexp; handlers, muxes and server timeouts are in net/http: Server, Client, 1.22 Routing; wrapping handlers (security headers, logging, recover) is in Middlewares; password hashing, session stores and the full CSRF design are in Authentication in Go; embed and fs.FS are in Files, Directories, Paths, Temp Files, bufio & embed; the threat model behind escaping and CSRF is in OWASP Top 10; and where a view sits in MVC is in Interaction & Presentation: MVC.

Facts below were checked against the Go 1.27 standard-library sources on go.dev (html/template doc.go, escape.go, error.go, template.go, content.go; text/template doc.go; embed; net/http csrf.go and cookie.go; pkg.go.dev returns 403 to scripted fetches), the Go 1.5, 1.8, 1.9, 1.10, 1.16, 1.21, 1.22, 1.23, 1.24 and 1.25 release notes, the OWASP XSS and CSRF cheat sheets, MDN on CSP nonces and on the 303 status, the htmx reference, the READMEs of templ, gomponents, gorilla/csrf and alexedwards/scs, and the Laravel 13 Blade, session, CSRF, validation, localization and Vite documentation. Snippets declare go 1.24 (they use b.Loop and slog.DiscardHandler, which are Go 1.24 additions, and for range n, a Go 1.22 language feature), use only the standard library, and every test passed with -race on Go 1.27.4.

Page map ​

If you are looking forGo to
The tables you can memorise in one minuteEverything in one minute
Why a template engine must escape for youWhy it exists
Which Go release added whatWhere it comes from
A text/template page that leaks, and the fixGo
html/template vs text/templatePackage choice
One action encoded five waysContextual auto-escaping
template.HTML, JS, URL and the trust boundaryTyped strings
ParseFS with embedEmbedded templates
define, block, templateTemplate inheritance
Layouts, partials, two pages defining the same blockLayouts, partials and name clashes
Parse once, Clone, dev-mode reloadCaching
Structs, maps, dot, $Passing data
Pipelines, range, with, if, else withActions and pipelines
FuncMap, eq, lt, printf, indexFunctions
{{- and -}}Whitespace control
A field partial that takes four valuesNested templates with data
Error before headers, bytes.Buffer, sync.PoolRender to a buffer
ParseForm, validation, sticky valuesForms
POST then 303Post/Redirect/Get
Hidden token, double submit, CrossOriginProtectionCSRF
Signed cookie, one-shot messageFlash messages
Plural forms, translationsi18n and pluralization
app.3f2a9c1b.css, immutableStatic assets and cache busting
HX-Request, fragments, Varyhtmx partials
script-src 'nonce-...'CSP nonces
templ, gomponents, BladeAlternatives
ErrBranchEnd, ZgotmplZ, exact messagesMechanics
The common bugs and their fixesSolving the classic problems
What to use whenChoosing
Monolith to distributed systemIn architecture
Reproduce it on your machineLab
@extends, @csrf, @error, old()For PHP/Laravel developers

The phrases below are the ones people type into a search box; each row points at the section that answers it.

PhraseWhere
html/template vs text/templatePackage choice
contextual auto-escapingContextual auto-escaping
template.HTML trustTyped strings
ParseFS with embedEmbedded templates
template inheritance (define, block, template)Template inheritance
layouts and partials, template sets and name clashesLayouts, partials and name clashes
template caching (parse once, Clone), dev-mode reloadCaching
data passing (structs, maps, dot)Passing data
pipelines, range/with/ifActions and pipelines
functions and FuncMap, comparison functions, printf, indexFunctions
whitespace control {{- -}}Whitespace control
nested templates with dataNested templates with data
rendering to a buffer then writing (error before headers)Render to a buffer
forms (ParseForm, validation errors re-rendering, PRG pattern)Forms, Post/Redirect/Get
CSRF token in formsCSRF
flash messages via session cookieFlash messages
i18n/pluralization pointeri18n and pluralization
static assets and cache bustingStatic assets and cache busting
partial rendering for htmxhtmx partials
Content-Security-Policy with noncesCSP nonces
templ/gomponents comparisonAlternatives
Laravel Blade comparisonFor PHP/Laravel developers

Everything in one minute ​

The page-building cast. Every row is unpacked in the concept catalogue.

PiecePackage and callPlain wordsDone when
Template settemplate.New("").Funcs(m).ParseFS(fsys, "layouts/*.gohtml", "partials/*.gohtml")Layout and partials, parsed onceAt start-up
Page clonebase.Clone() then t.ParseFS(fsys, "pages/home.gohtml")Base plus one page's define blocksAt start-up, once per page
Executet.ExecuteTemplate(&buf, "base", page)Run the layout against the dataPer request, into a buffer
Sendw.WriteHeader(status) then buf.WriteTo(w)Nothing leaves before the render succeededPer request
Formr.ParseForm(), r.PostForm, validationRead what the browser sentPer POST
Redirecthttp.Redirect(w, r, "/", http.StatusSeeOther)Turn a POST into a GETAfter success
Tokenhidden csrf_token plus cookieProves the form came from your pageEvery unsafe request
Flashsigned cookie, popped on the next pageOne message, shown onceAfter the redirect

The actions you use every day. The delimiters are two opening braces and two closing braces; the examples are written in the table with a v-pre marker because Vue would otherwise try to evaluate them.

ActionPlain wordsExample
OutputPrint a value, escaped for its context{{ .Title }}
if / else if / elseBranch on truthiness{{ if .User }}...{{ else }}...{{ end }}
range / elseLoop; else runs when empty{{ range .Items }}...{{ else }}none{{ end }}
with / else withRebind dot when non-empty (else with: Go 1.23){{ with .Flash }}{{ .Text }}{{ end }}
defineName a template{{ define "nav" }}...{{ end }}
templateCall a named template; dot is what you pass{{ template "nav" . }}
blockdefine plus call, with default content{{ block "content" . }}default{{ end }}
VariableKeep a value; $ is the root dot{{ $n := len .Items }}
PipelineFeed the left value to the right function{{ .Total | money | printf "EUR %s" }}
TrimRemove adjacent whitespace{{- if .X -}}
CommentDropped from the output{{/* note */}}

The typed strings that switch escaping off. Each is a promise from the developer, never a conversion of user input.

Type (html/template)HoldsWhere it is honoured
template.HTMLA safe HTML fragmentHTML text
template.HTMLAttrA safe attribute name and valueAttribute position
template.JSA safe JavaScript expressionScript blocks and event handlers
template.JSStrA safe sequence of string charactersInside a JS string literal
template.CSSSafe CSSStyle blocks and attributes
template.URLA safe URLhref, src
template.SrcsetA safe srcset value (Go 1.10)srcset attributes

The errors you will meet.

Message (shortened)ErrorCodeWhat it means
appears in an ambiguous context within a URLErrAmbigContextThe escaper cannot tell whether the action is a path or a query
branches end in different contextsErrBranchEndAn if leaves the parser in a different state on each branch
cannot Parse after Execute(plain error)Templates are frozen once executed
cannot Clone ... after it has executed(plain error)Clone before the first run
pattern matches no files(from ParseFS)A glob in ParseFS found nothing
nil pointer evaluating(execution error)Dot walked through a nil
#ZgotmplZ in the output(not an error)The value failed the URL or CSS filter

Why it exists ​

The first server-rendered pages were written with string concatenation: "<p>Hello, " + name + "</p>". It works until name is <script>...</script>, at which point the data has become code. Cross-site scripting stays near the top of every web security list because the fix is not one escape call but coverage: OWASP puts it plainly, "Coverage is what matters: an application that protects 99 places and misses one is still vulnerable." A template engine that escapes by default and by context moves that coverage from the developer's memory into the engine.

Server rendering is also an architecture choice. A handler that returns finished HTML needs no client-side framework, works with JavaScript disabled, is cacheable as a document and puts the whole view next to the code that knows the data. The price is that the server must get four things right on every page: escaping, error handling before the first byte, the form round trip, and the tokens and headers that make forms and inline scripts safe.

String concatenation or text/templatehtml/template
You escape by hand, in every placeEscaping is added to every action at first execution
One forgotten call is an XSS holeA forgotten call is not possible; a mis-trusted type is
Same escaping everywhere (or none)Different encoder for text, attribute, URL, JavaScript and CSS
Fast, dangerousA little slower, safe by default
Works for plain text, e-mail, configMeant for HTML only
Any template shape parsesSome shapes are rejected (ErrBranchEnd, ErrAmbigContext)

An everyday picture. A mail-merge letter. The author writes the letter once and marks the gaps; the clerk fills the gaps from a list the author does not control, and the clerk is trained never to let a name in the list change the letter itself: a name that says "ignore the letter and wire me money" is printed as a name, in quotation marks if it has to be. The clerk knows what kind of gap it is: a gap inside a sentence, inside a web address, inside a phone number, each with its own rules for what may be written. The clerk is html/template; the list is your database and your users.

Three common misunderstandings, up front ​

  1. "html/template is text/template with an escape function." It parses the template as HTML and rewrites every action at first execution according to where it sits. The same {{ .X }} is encoded differently in text, in an attribute, in a URL and in a script.
  2. "If I use html/template I cannot have an XSS." You can, by calling template.HTML on data you did not sanitise, by putting data in a context the package documents as unsafe (JavaScript outside its safe subset), or by echoing a URL scheme you whitelisted wrongly. The package protects the author's structure, not the author's decisions.
  3. "Template files are parsed when the page is requested." Parse them once at start-up; parsing per request is what most tutorials do and what costs an order of magnitude more per page (see the lab).

Where it comes from ​

html/template wraps text/template: its documentation says it "provides the same interface as text/template and should be used instead of text/template whenever the output is HTML", and that its security model "assumes that template authors are trusted, while Execute's data parameter is not". It states three properties it seeks to keep in the face of untrusted data (Structure Preservation, Code Effect, Least Surprise), quoted from the safe-template definition it cites. The package has changed in small, mostly security-driven steps:

1  Go 1.5   text/template and html/template: integer constants too large for an int are a parse error;
            Template.Option arrives (the one option: missingkey)
2  Go 1.8   html/template validates the "type" attribute of <script>
3  Go 1.9   a predefined escaper ("html", "urlquery", "js") in a pipeline that does not match is an error
4  Go 1.10  Srcset content type
5  Go 1.16  template.ParseFS and Template.ParseFS read templates from an fs.FS; //go:embed arrives
6  Go 1.18  text/template: {{break}} and {{continue}} inside range
7  Go 1.21  exported ErrJSTemplate for actions inside JavaScript template literals
8  Go 1.22  JavaScript template literals may contain actions; ErrJSTemplate is no longer returned
9  Go 1.23  text/template: "else with"
10 Go 1.24  (February 2025) text/template: range over integers and over functions
11 Go 1.25  (August 2025) net/http.CrossOriginProtection: token-less CSRF defence from Sec-Fetch-Site and Origin

The surrounding practice has a history of its own. The synchronizer token pattern for CSRF is the OWASP default for stateful applications; the Post/Redirect/Get idea is as old as browsers re-asking "resubmit the form?"; the 303 status code exists for it (MDN: "the browser should redirect to the URL in the Location header instead of rendering the requested resource", and "the method to retrieve the redirected resource is always GET"); CSP nonces replaced long allow-lists because, as MDN puts it, "a nonce is the recommended approach for restricting the loading of <script> and <style> resources". The Go 1.22 JavaScript change is a reminder that the escaper's JavaScript support is deliberately narrow: the doc says that outside its safe subset "escaping is best-effort and safety cannot be assured".

Go ​

Before ​

A handler written the way tutorials write it: text/template because the name is shorter to remember, a parse on every request, and Execute straight into the ResponseWriter. It works on a quiet day. It fails in three ways: the name from the query string is printed unescaped, parsing costs more than rendering, and an error halfway through the page has already sent 200 OK and half a document.

go
// Package before shows a server-rendered page done the tempting way:
// text/template, parsed on every request, written straight to the
// ResponseWriter. It works on a quiet day and fails in three ways.
package before

import (
	"net/http"
	"text/template" // wrong package for HTML output: no escaping
)

const page = `<!doctype html>
<html>
<head><title>Hello</title></head>
<body>
<h1>Hello, {{.Name}}</h1>
<ul>
{{range .Items}}<li>{{.Title}} costs {{.Price.Amount}}</li>
{{end}}</ul>
</body>
</html>`

// Item is one row of the page.
type Item struct {
	Title string
	Price *Money // nil for "price on request": a nil dereference during execution
}

// Money is a price.
type Money struct{ Amount int }

// Data is what the template receives.
type Data struct {
	Name  string
	Items []Item
}

// Handler parses the template on every request and executes it into the
// ResponseWriter. The status line and the first bytes of the body are
// already on the wire when an error shows up halfway through.
func Handler(items []Item) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		t, err := template.New("page").Parse(page) // parse per request: wasted work
		if err != nil {
			http.Error(w, "template error", http.StatusInternalServerError)
			return
		}
		w.Header().Set("Content-Type", "text/html; charset=utf-8")
		// The name comes straight from the query string and is not escaped.
		data := Data{Name: r.URL.Query().Get("name"), Items: items}
		if err := t.Execute(w, data); err != nil {
			// Too late: 200 and half a page are gone. This call cannot
			// change the status any more.
			http.Error(w, "template error", http.StatusInternalServerError)
		}
	}
}

The test proves two of the three: the script tag survives untouched, and a nil price in the second row yields status 200, a truncated page and the error text glued to the end of it.

go
package before

import (
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
)

func TestNameIsNotEscaped(t *testing.T) {
	h := Handler([]Item{{Title: "pen", Price: &Money{Amount: 3}}})
	rec := httptest.NewRecorder()
	h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/?name=%3Cscript%3Ealert(1)%3C/script%3E", nil))
	if !strings.Contains(rec.Body.String(), "<script>alert(1)</script>") {
		t.Fatalf("text/template should have left the script tag intact:\n%s", rec.Body)
	}
}

func TestErrorAfterHeadersGivesStatus200AndHalfAPage(t *testing.T) {
	h := Handler([]Item{{Title: "pen", Price: &Money{Amount: 3}}, {Title: "gift", Price: nil}})
	rec := httptest.NewRecorder()
	h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/?name=Ann", nil))
	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d, want 200 (the failure came too late to change it)", rec.Code)
	}
	body := rec.Body.String()
	if !strings.Contains(body, "pen costs 3") || strings.Contains(body, "</html>") {
		t.Fatalf("expected a truncated page, got:\n%s", body)
	}
	if !strings.Contains(body, "template error") {
		t.Fatalf("the error text is glued to the broken page:\n%s", body)
	}
}

After ​

The same idea built as a small site. Templates live in an embedded tree and are parsed once; every page is a clone of the shared layout plus its own define blocks; rendering goes to a buffer; forms are validated and re-rendered with 422; a valid POST redirects with 303 and a flash cookie; every form carries a CSRF token; the CSP header carries a per-response nonce; the stylesheet URL carries a content hash; and /items answers an htmx request with a fragment. The wiring is short because each piece is small.

go
// Package app wires the pieces into one server-rendered site: embedded
// templates, flash messages, a CSRF token in every form, a CSP nonce, a
// fingerprinted static route, post/redirect/get and an htmx fragment.
package app

import (
	"html/template"
	"io/fs"
	"log/slog"
	"net/http"
	"os"
	"strconv"
	"time"

	"academy/templates-server-rendering/assets"
	"academy/templates-server-rendering/csp"
	"academy/templates-server-rendering/csrf"
	"academy/templates-server-rendering/flash"
	"academy/templates-server-rendering/forms"
	"academy/templates-server-rendering/funcs"
	"academy/templates-server-rendering/render"
)

// Item is one row of the items page.
type Item struct {
	Name  string
	Qty   int
	Cents int64
}

// ItemsData is the dot of the items page and of its htmx fragment.
type ItemsData struct {
	Items []Item
	Next  int
}

// App holds what every handler needs.
type App struct {
	r     *render.Renderer
	flash *flash.Manager
	log   *slog.Logger
	items []Item
	now   func() time.Time
}

// New builds the handler tree. key signs the flash and CSRF values. When
// devTemplates is a directory, templates are read from it and re-parsed on every
// request (edit, refresh, see); when it is empty the embedded tree is parsed once.
func New(key []byte, devTemplates string, log *slog.Logger) (http.Handler, error) {
	reg, err := assets.New(assets.FS(), "/static")
	if err != nil {
		return nil, err
	}
	fm := funcs.Map()
	fm["asset"] = reg.Path // {{asset "app.css"}} -> /static/app.<hash>.css
	var tplFS fs.FS = render.FS()
	if devTemplates != "" {
		tplFS = os.DirFS(devTemplates)
	}
	r, err := render.New(tplFS, template.FuncMap(fm), devTemplates != "")
	if err != nil {
		return nil, err
	}
	a := &App{r: r, flash: flash.New(key), log: log, now: time.Now, items: []Item{
		{"pen", 1, 250}, {"ink", 3, 1999}, {"paper", 500, 899}, {"stapler", 1, 1290},
	}}

	pages := http.NewServeMux()
	pages.HandleFunc("GET /{$}", a.home)
	pages.HandleFunc("GET /items", a.itemsPage)
	pages.HandleFunc("GET /contact", a.contactForm)
	pages.HandleFunc("POST /contact", a.contactSubmit)

	root := http.NewServeMux()
	root.Handle("/static/", reg.Handler())
	root.Handle("/", csp.Middleware(csrf.Protect(key, false, nil, pages)))
	return root, nil
}

// page builds the dot for the layout from the request.
func (a *App) page(w http.ResponseWriter, r *http.Request, data any) render.Page {
	p := render.Page{Nonce: csp.Nonce(r.Context()), CSRF: csrf.Token(r.Context()), Data: data}
	if m, ok := a.flash.Pop(w, r); ok {
		p.Flash = &render.Flash{Level: m.Level, Text: m.Text}
	}
	return p
}

// show renders a page, or answers 500 when the template fails. Because the
// renderer buffers, a failure here has not sent a single byte yet.
func (a *App) show(w http.ResponseWriter, r *http.Request, status int, page string, data any) {
	if err := a.r.Render(w, status, page, a.page(w, r, data)); err != nil {
		a.log.Error("render failed", "page", page, "err", err)
		http.Error(w, "Internal Server Error", http.StatusInternalServerError)
	}
}

func (a *App) home(w http.ResponseWriter, r *http.Request) {
	a.show(w, r, http.StatusOK, "home", a.now())
}

func (a *App) contactForm(w http.ResponseWriter, r *http.Request) {
	a.show(w, r, http.StatusOK, "contact", forms.New(nil))
}

func (a *App) contactSubmit(w http.ResponseWriter, r *http.Request) {
	f, err := forms.Decode(w, r)
	if err != nil {
		http.Error(w, "Bad Request", http.StatusBadRequest)
		return
	}
	f.Required("email")
	f.Email("email")
	f.Required("message")
	f.MaxRunes("message", 500)
	if !f.Valid() {
		// 422: the same URL, the same form, errors and the typed values kept.
		a.show(w, r, http.StatusUnprocessableEntity, "contact", f)
		return
	}
	// ... store or send the message here ...
	a.flash.Set(w, flash.Message{Level: "success", Text: "Thanks, we will answer soon."})
	http.Redirect(w, r, "/", http.StatusSeeOther) // 303: the browser follows with GET, F5 cannot re-POST
}

func (a *App) itemsPage(w http.ResponseWriter, r *http.Request) {
	pageNo, _ := strconv.Atoi(r.URL.Query().Get("page"))
	if pageNo < 1 {
		pageNo = 1
	}
	data := ItemsData{Items: a.items, Next: pageNo + 1}
	// The same URL answers two shapes chosen by two headers, so caches must key on both.
	w.Header().Add("Vary", "HX-Request, HX-Boosted")
	// A boosted link also sends HX-Request but swaps the whole body: full page.
	if r.Header.Get("HX-Request") == "true" && r.Header.Get("HX-Boosted") != "true" {
		if err := a.r.RenderBlock(w, http.StatusOK, "items", "item-list", data); err != nil {
			a.log.Error("render fragment failed", "err", err)
			http.Error(w, "Internal Server Error", http.StatusInternalServerError)
		}
		return
	}
	a.show(w, r, http.StatusOK, "items", data)
}

The test drives the whole site through httptest.NewServer and a cookie jar, the way a browser would: nonce in the header equals nonce in the body, a POST without a token gets 403, an invalid form gets 422 with escaped sticky values, a valid form gets 303 and the flash appears exactly once, a fragment request gets a fragment and a boosted request gets the full page.

go
package app

import (
	"html"
	"io"
	"log/slog"
	"net/http"
	"net/http/cookiejar"
	"net/http/httptest"
	"net/url"
	"os"
	"path/filepath"
	"regexp"
	"strings"
	"testing"

	"academy/templates-server-rendering/render"
)

var key = []byte("0123456789abcdef0123456789abcdef")

type site struct {
	t   *testing.T
	srv *httptest.Server
	c   *http.Client
}

func newSite(t *testing.T) *site {
	t.Helper()
	h, err := New(key, "", slog.New(slog.DiscardHandler))
	if err != nil {
		t.Fatal(err)
	}
	srv := httptest.NewServer(h)
	t.Cleanup(srv.Close)
	jar, _ := cookiejar.New(nil)
	c := &http.Client{Jar: jar, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
	return &site{t: t, srv: srv, c: c}
}

func (s *site) do(req *http.Request) (*http.Response, string) {
	s.t.Helper()
	resp, err := s.c.Do(req)
	if err != nil {
		s.t.Fatal(err)
	}
	defer resp.Body.Close()
	b, _ := io.ReadAll(resp.Body)
	return resp, string(b)
}

func (s *site) get(path string, hdr ...string) (*http.Response, string) {
	req, _ := http.NewRequest(http.MethodGet, s.srv.URL+path, nil)
	for i := 0; i+1 < len(hdr); i += 2 {
		req.Header.Set(hdr[i], hdr[i+1])
	}
	return s.do(req)
}

func (s *site) post(path string, v url.Values) (*http.Response, string) {
	req, _ := http.NewRequest(http.MethodPost, s.srv.URL+path, strings.NewReader(v.Encode()))
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	return s.do(req)
}

var tokenRe = regexp.MustCompile(`name="csrf_token" value="([^"]+)"`)

func (s *site) token() string {
	s.t.Helper()
	_, body := s.get("/contact")
	m := tokenRe.FindStringSubmatch(body)
	if m == nil {
		s.t.Fatalf("no csrf token in\n%s", body)
	}
	return m[1]
}

func TestPagesCarryNonceMatchingThePolicy(t *testing.T) {
	s := newSite(t)
	resp, body := s.get("/")
	if resp.StatusCode != 200 {
		t.Fatalf("status %d", resp.StatusCode)
	}
	policy := resp.Header.Get("Content-Security-Policy")
	m := regexp.MustCompile(`'nonce-([^']+)'`).FindStringSubmatch(policy)
	if m == nil {
		t.Fatalf("no nonce in policy %q", policy)
	}
	// html/template escapes "+" in the attribute as &#43;; the browser decodes
	// it again, so compare the decoded values.
	attrs := regexp.MustCompile(`<script nonce="([^"]*)"`).FindAllStringSubmatch(body, -1)
	if len(attrs) != strings.Count(body, "<script") || len(attrs) == 0 {
		t.Fatalf("every script tag in the layout must carry a nonce attribute:\n%s", body)
	}
	for _, a := range attrs {
		if html.UnescapeString(a[1]) != m[1] {
			t.Fatalf("nonce mismatch\npolicy: %s\nattribute: %s", policy, a[1])
		}
	}
}

func TestStaticAssetUsesFingerprintAndImmutableCache(t *testing.T) {
	s := newSite(t)
	_, body := s.get("/")
	m := regexp.MustCompile(`href="(/static/app\.[0-9a-f]{8}\.css)"`).FindStringSubmatch(body)
	if m == nil {
		t.Fatalf("no fingerprinted css link in\n%s", body)
	}
	resp, _ := s.get(m[1])
	if resp.StatusCode != 200 || !strings.Contains(resp.Header.Get("Cache-Control"), "immutable") {
		t.Fatalf("static: %d %v", resp.StatusCode, resp.Header)
	}
}

func TestPostWithoutTokenIsForbidden(t *testing.T) {
	s := newSite(t)
	resp, _ := s.post("/contact", url.Values{"email": {"ann@example.test"}, "message": {"hi"}})
	if resp.StatusCode != http.StatusForbidden {
		t.Fatalf("status %d", resp.StatusCode)
	}
}

func TestInvalidFormIsRerenderedWith422AndStickyValues(t *testing.T) {
	s := newSite(t)
	tok := s.token()
	resp, body := s.post("/contact", url.Values{"csrf_token": {tok}, "email": {`x"><script>alert(1)</script>`}, "message": {""}})
	if resp.StatusCode != http.StatusUnprocessableEntity {
		t.Fatalf("status %d", resp.StatusCode)
	}
	if strings.Contains(body, "<script>alert(1)") {
		t.Fatal("the sticky value must be escaped")
	}
	for _, want := range []string{"Enter a valid email address", "This field is required", `value="x&#34;&gt;&lt;script&gt;alert(1)&lt;/script&gt;"`} {
		if !strings.Contains(body, want) {
			t.Errorf("missing %q in\n%s", want, body)
		}
	}
}

func TestPostRedirectGetShowsFlashOnce(t *testing.T) {
	s := newSite(t)
	tok := s.token()
	resp, _ := s.post("/contact", url.Values{"csrf_token": {tok}, "email": {"ann@example.test"}, "message": {"hello"}})
	if resp.StatusCode != http.StatusSeeOther || resp.Header.Get("Location") != "/" {
		t.Fatalf("want 303 to /, got %d %q", resp.StatusCode, resp.Header.Get("Location"))
	}
	_, first := s.get("/")
	if !strings.Contains(first, `class="flash flash-success"`) || !strings.Contains(first, "Thanks, we will answer soon.") {
		t.Fatalf("flash missing after redirect:\n%s", first)
	}
	_, second := s.get("/")
	if strings.Contains(second, "flash-success") {
		t.Fatal("flash must disappear on the next page")
	}
}

func TestHTMXFragmentVersusFullPage(t *testing.T) {
	s := newSite(t)
	resp, frag := s.get("/items", "HX-Request", "true")
	if strings.Contains(frag, "<html") || !strings.Contains(frag, `<ul id="item-list">`) {
		t.Fatalf("expected a fragment:\n%s", frag)
	}
	if v := strings.Join(resp.Header.Values("Vary"), ","); !strings.Contains(v, "HX-Request") || !strings.Contains(v, "HX-Boosted") {
		t.Errorf("Vary = %q: both headers select the representation", v)
	}
	boostedResp, _ := s.get("/items", "HX-Request", "true", "HX-Boosted", "true")
	if v := strings.Join(boostedResp.Header.Values("Vary"), ","); !strings.Contains(v, "HX-Boosted") {
		t.Errorf("boosted response Vary = %q", v)
	}
	_, full := s.get("/items")
	if !strings.Contains(full, "<html") || !strings.Contains(full, `hx-get="/items?page=2"`) {
		t.Fatalf("expected the full page:\n%s", full)
	}
	_, boosted := s.get("/items", "HX-Request", "true", "HX-Boosted", "true")
	if !strings.Contains(boosted, "<html") {
		t.Fatal("a boosted request swaps the body and needs the full page")
	}
}

func TestUnknownPathIs404(t *testing.T) {
	s := newSite(t)
	if resp, _ := s.get("/nope"); resp.StatusCode != http.StatusNotFound {
		t.Fatalf("status %d", resp.StatusCode)
	}
}

func TestDevModeReloadsTemplatesFromDisk(t *testing.T) {
	dir := t.TempDir()
	if err := os.CopyFS(dir, render.FS()); err != nil {
		t.Fatal(err)
	}
	h, err := New(key, dir, slog.New(slog.DiscardHandler))
	if err != nil {
		t.Fatal(err)
	}
	srv := httptest.NewServer(h)
	defer srv.Close()
	fetch := func() string {
		resp, err := http.Get(srv.URL + "/")
		if err != nil {
			t.Fatal(err)
		}
		defer resp.Body.Close()
		b, _ := io.ReadAll(resp.Body)
		return string(b)
	}
	if strings.Contains(fetch(), "EDITED ON DISK") {
		t.Fatal("marker present before the edit")
	}
	f := filepath.Join(dir, "pages", "home.gohtml")
	b, _ := os.ReadFile(f)
	edited := strings.Replace(string(b), "<h1>Welcome</h1>", "<h1>EDITED ON DISK</h1>", 1)
	if err := os.WriteFile(f, []byte(edited), 0o644); err != nil {
		t.Fatal(err)
	}
	if !strings.Contains(fetch(), "EDITED ON DISK") {
		t.Fatal("dev mode must pick up an on-disk edit without a restart")
	}
}

func TestLayoutLoadsVendoredHTMX(t *testing.T) {
	s := newSite(t)
	_, body := s.get("/items")
	m := regexp.MustCompile(`src="(/static/htmx\.min\.[0-9a-f]{8}\.js)"`).FindStringSubmatch(body)
	if m == nil {
		t.Fatalf("layout must load the vendored htmx from /static:\n%s", body)
	}
	if resp, b := s.get(m[1]); resp.StatusCode != 200 || !strings.Contains(b, "htmx") {
		t.Fatalf("htmx asset: %d", resp.StatusCode)
	}
	if !strings.Contains(body, `"includeIndicatorStyles":false`) {
		t.Error("htmx injects an inline style; the CSP forbids it, so the meta config must switch it off")
	}
}

The Go angle ​

Go's standard library ships the whole server-rendering toolkit: html/template for the page, embed and io/fs for the files, net/http for forms, cookies and redirects, crypto/hmac and crypto/rand for signing and tokens, net/mail for address validation, and since Go 1.25 http.CrossOriginProtection for token-less CSRF defence. What it deliberately leaves out is the glue: there is no layout system, no flash helper, no form-validation library, no asset pipeline. The snippets above are that glue in about 950 lines including the templates and static files (without tests); most teams copy a version of it once and keep it. Three properties make it pleasant: templates are plain files that embed bakes into the binary (one file to deploy), a compiled *template.Template is safe for concurrent use ("a template may be executed safely in parallel"), and everything is testable with httptest without a browser.

The concept catalogue ​

html/template vs text/template Must-know ​

In plain words: The two packages have the same API and the same template language. text/template prints what it is given; html/template also understands that the output is HTML and encodes every value for the place it lands. Use html/template for anything a browser will parse.

Common misunderstanding: "I will use text/template and call template.HTMLEscapeString where needed." That is the string-concatenation discipline again: it works exactly as long as nobody forgets, and it picks one encoding for all contexts, which is wrong for attributes, URLs and scripts. The doc's own example prints Hello, <script>alert('you have been pwned')</script>! with text/template and Hello, &lt;script&gt;alert(&#39;you have been pwned&#39;)&lt;/script&gt;! with html/template.

Definition: html/template "wraps text/template so you can share its template API to parse and execute HTML templates safely". If parsing and execution succeed, the output is injection-safe in the package's security model; otherwise the error is "defined in the docs for ErrorCode". Template authors are trusted, the data argument is not.

1  t := text.New("t").Parse(`<p>{{.}}</p>`)         Execute(w, "<b>x</b>")  ->  <p><b>x</b></p>
2  t := html.New("t").Parse(`<p>{{.}}</p>`)         Execute(w, "<b>x</b>")  ->  <p>&lt;b&gt;x&lt;/b&gt;</p>
3  t := html.New("t").Parse(`<p>{{.}}</p>`)         Execute(w, template.HTML("<b>x</b>"))  ->  <p><b>x</b></p>   // you vouched for it

Real scenario: a comment form that echoes the comment on the next page; a profile page that prints a display name inside an alt attribute; a search page that puts the query in a link; a plain-text e-mail template, where text/template is correct because there is no HTML to protect; a Markdown renderer whose output is trusted HTML only after sanitising.

Output isPackageWhy
HTML page or fragmenthtml/templateContextual escaping
Plain-text e-mail, log line, config file, SQL migrationtext/templateNo markup to protect; html/template would encode ' and &
HTML e-mailhtml/templateIt is HTML
JSONencoding/jsonNeither template package knows JSON syntax
Source code generationtext/templateEscaping would corrupt it

Fix / how to use it: import html/template, never text/template, in any file that renders pages; some teams add a linter rule (depguard in golangci-lint) banning text/template in the web package. The escaping snippet below shows what the package does per context.

Contextual auto-escaping Must-know ​

In plain words: Before the first run, the package reads your template like a browser would and works out, for every action, whether it sits in text, in a quoted attribute, in a URL, in a script or in CSS. It then adds the matching encoder to the action. You write {{ .Name }}; the engine writes {{ .Name | htmlescaper }} or {{ .Name | urlescaper | attrescaper }} for you.

Common misunderstanding: "Escaping is HTML-escaping." HTML-escaping javascript:alert(1) leaves it intact, and it is still dangerous in an href. Each context has its own dangerous characters: < in text, " in an attribute, & and # in a URL query, \ and quotes in a JavaScript string. The engine chooses per position.

Definition: The package "understands HTML, CSS, JavaScript, and URIs. It adds sanitizing functions to each simple action pipeline". At parse (really: first execute) time, the action in <a href="/search?q=...">...</a> becomes . | urlescaper | attrescaper for the attribute and . | htmlescaper for the text. If an action evaluates to a nil interface value it is treated as an empty string. Attributes with a namespace or a data- prefix are treated as if they had none, so data-href is a URL attribute, and any xmlns: attribute is treated as a URL.

1  value = O'Reilly: <i>"hi"</i> & more
2  <p>{{.}}</p>                 -> O&#39;Reilly: &lt;i&gt;&#34;hi&#34;&lt;/i&gt; &amp; more
3  <a title="{{.}}">            -> the same encoding: attribute value, quotes encoded
4  <a href="/files/{{.}}">      -> O%27Reilly:%20%3ci%3e%22hi%22%3c/i%3e%20&amp;%20more     (path: "/" kept)
5  <a href="/search?q={{.}}">   -> O%27Reilly%3a%20%3ci%3e%22hi%22%3c%2fi%3e%20%26%20more   (query: "/" and "&" encoded)
6  <a href="{{.}}">             -> #ZgotmplZ     (a whole URL must start with an allowed scheme)
7  <script>var s = "{{.}}"</script> -> O'Reilly: <i>"hi"<\/i> & more
8  <script>var v = {{.}}</script>   -> "O'Reilly: <i>\"hi\"</i> & more"   (a JSON string)
9  <p style="color: {{.}}">         -> ZgotmplZ      (not a valid CSS value)

The nine lines are the real output of the escaping test below (run with -v). Line 8 shows how non-string values behave in a script: a struct or map is marshalled as JSON, so var v = {{.}} receives a JavaScript object.

Real scenario: a user-supplied display name in a heading, in a title attribute and in a URL parameter on the same page; a redirect target ?next= that an attacker sets to javascript:; a JSON blob for a chart embedded in a <script> tag; a colour picked by the user and echoed into style.

ContextAdded encoder (internal name)Dangerous inputResult
HTML texthtmlescaper<script>&lt;script&gt;
Quoted attributeattrescaper" onmouseover="x&#34; onmouseover=&#34;x
URL query valueurlescaper, then attrescapera&b=ca%26b%3dc
Whole URLurlfilter, then attrescaperjavascript:alert(1)#ZgotmplZ
JS stringjsstrescaper</script><\/script>
JS valuejsvalescaperstructJSON
CSS valueCSS filterexpression(...)ZgotmplZ
Commentsremoved<!-- secret -->nothing (comments are stripped, except for the typed HTML, CSS, JS)
One action, five encoders: html/template reads the context at parse timethe action {{.}}data: O'Reilly: <i>x</i>HTML text<p>{{.}}</p>htmlescaperO&#39;Reilly: &lt;i&gt;x&lt;/i&gt;quoted attribute<a title="{{.}}">attrescaperO&#39;Reilly: &lt;i&gt;x&lt;/i&gt;URL query<a href="/s?q={{.}}">urlescaper, attrescaperO%27Reilly%3a%20%3ci%3e...JS string<script>s = "{{.}}"</script>jsstrescaperO\u0027Reilly: \u003ci\u003ex...whole URL<a href="{{.}}">urlfilterjavascript:... becomes #ZgotmplZContextTemplate sourceEncoder in the pipelineOutputThe author is trusted, the data is not. template.HTML, JS, URL and friends mark a value as already safe: they switch the encoder off.

Fix / how to use it: do nothing; the point is that you do not escape. Where the output is wrong, fix the data type or the position, not the encoder. Put values into attribute-quoted positions (value="..."), never into unquoted ones, and keep JavaScript outside the page where you can: the documentation advises "to pass template data to a complex JavaScript program, use a dedicated <script> element to initialize variables and keep complex program logic in separate elements or external files".

go
// Package escaping shows html/template's contextual auto-escaping: the same
// action {{.}} is encoded differently depending on where it sits in the page.
package escaping

import (
	"bytes"
	"html/template"
)

// Render executes src with data and returns the output.
func Render(src string, data any) (string, error) {
	t, err := template.New("t").Parse(src)
	if err != nil {
		return "", err
	}
	var buf bytes.Buffer
	if err := t.Execute(&buf, data); err != nil {
		return "", err
	}
	return buf.String(), nil
}

// Contexts are the snippets whose action sits in a different context each.
var Contexts = []struct {
	Name string
	Src  string
}{
	{"html text", `<p>{{.}}</p>`},
	{"quoted attribute", `<a title="{{.}}">x</a>`},
	{"url path", `<a href="/files/{{.}}">x</a>`},
	{"url query", `<a href="/search?q={{.}}">x</a>`},
	{"url whole", `<a href="{{.}}">x</a>`},
	{"js string", `<script>var s = "{{.}}";</script>`},
	{"js value", `<script>var v = {{.}};</script>`},
	{"css value", `<p style="color: {{.}}">x</p>`},
}

// TrustedHTML marks s as safe HTML. From now on the escaper steps aside, so
// the caller promises that s came from a sanitizer or from the developer.
func TrustedHTML(s string) template.HTML {
	return template.HTML(s) //nolint:gosec // illustration: the trust boundary is this conversion
}
go
package escaping

import (
	"errors"
	"html/template"
	"strings"
	"testing"
)

const evil = `O'Reilly: <i>"hi"</i> & more`

func TestEachContextEncodesDifferently(t *testing.T) {
	want := map[string]string{
		"html text":        `<p>O&#39;Reilly: &lt;i&gt;&#34;hi&#34;&lt;/i&gt; &amp; more</p>`,
		"quoted attribute": `<a title="O&#39;Reilly: &lt;i&gt;&#34;hi&#34;&lt;/i&gt; &amp; more">x</a>`,
		"url path":         `<a href="/files/O%27Reilly:%20%3ci%3e%22hi%22%3c/i%3e%20&amp;%20more">x</a>`,
		"url query":        `<a href="/search?q=O%27Reilly%3a%20%3ci%3e%22hi%22%3c%2fi%3e%20%26%20more">x</a>`,
		"js string":        `<script>var s = "O\u0027Reilly: \u003ci\u003e\u0022hi\u0022\u003c\/i\u003e \u0026 more";</script>`,
		"js value":         `<script>var v = "O'Reilly: \u003ci\u003e\"hi\"\u003c/i\u003e \u0026 more";</script>`,
	}
	for _, c := range Contexts {
		got, err := Render(c.Src, evil)
		if err != nil {
			t.Fatalf("%s: %v", c.Name, err)
		}
		t.Logf("%-17s %s", c.Name, got)
		if w, ok := want[c.Name]; ok && got != w {
			t.Errorf("%s:\n got  %s\n want %s", c.Name, got, w)
		}
	}
}

func TestDangerousURLSchemeIsReplaced(t *testing.T) {
	got, err := Render(`<a href="{{.}}">x</a>`, "javascript:alert(1)")
	if err != nil {
		t.Fatal(err)
	}
	if !strings.Contains(got, "#ZgotmplZ") {
		t.Fatalf("expected the failsafe value, got %s", got)
	}
}

func TestJSValueIsJSON(t *testing.T) {
	got, err := Render(`<script>var v = {{.}};</script>`, map[string]any{"a": "<b>", "n": 1})
	if err != nil {
		t.Fatal(err)
	}
	if !strings.Contains(got, `{"a":"\u003cb\u003e","n":1}`) {
		t.Fatalf("got %s", got)
	}
}

func TestTrustedHTMLSkipsEscaping(t *testing.T) {
	plain, _ := Render(`<p>{{.}}</p>`, "<b>bold</b>")
	trusted, _ := Render(`<p>{{.}}</p>`, TrustedHTML("<b>bold</b>"))
	if plain != `<p>&lt;b&gt;bold&lt;/b&gt;</p>` || trusted != `<p><b>bold</b></p>` {
		t.Fatalf("plain=%s trusted=%s", plain, trusted)
	}
	// The same conversion applied to attacker input is a stored XSS.
	bad, _ := Render(`<p>{{.}}</p>`, TrustedHTML(`<img src=x onerror=alert(1)>`))
	if !strings.Contains(bad, "onerror=alert(1)") {
		t.Fatalf("expected the payload to survive: %s", bad)
	}
}

func TestAmbiguousContextIsAnError(t *testing.T) {
	src := `<a href="{{if .C}}/path/{{else}}/search?q={{end}}{{.X}}">x</a>`
	_, err := Render(src, map[string]any{"C": true, "X": "v"})
	var te *template.Error
	if !errors.As(err, &te) || te.ErrorCode != template.ErrAmbigContext {
		t.Fatalf("want ErrAmbigContext, got %v", err)
	}
	t.Log(err)
}

func TestBranchesThatEndInDifferentContextsAreRejected(t *testing.T) {
	src := `{{if .}}<a href="{{end}}x`
	_, err := Render(src, true)
	var te *template.Error
	if !errors.As(err, &te) || te.ErrorCode != template.ErrBranchEnd {
		t.Fatalf("want ErrBranchEnd, got %v", err)
	}
	t.Log(err)
}

func TestEscapingHappensAtFirstExecuteNotAtParse(t *testing.T) {
	tpl, err := template.New("t").Parse(`<a href="{{if .C}}/p/{{else}}/s?q={{end}}{{.X}}">x</a>`)
	if err != nil {
		t.Fatalf("Parse should accept it: %v", err)
	}
	var sb strings.Builder
	if err := tpl.Execute(&sb, map[string]any{"C": true, "X": "v"}); err == nil {
		t.Fatal("Execute should fail: escaping runs at first execution")
	}
	if _, err := tpl.Parse(`{{define "x"}}y{{end}}`); err == nil {
		t.Fatal("Parse after Execute must fail")
	} else {
		t.Log(err)
	}
}

func TestTypedURLIsNotFiltered(t *testing.T) {
	got, err := Render(`<a href="{{.}}">x</a>`, template.URL("javascript:alert(1)"))
	if err != nil {
		t.Fatal(err)
	}
	t.Log(got)
	// The scheme filter is skipped, the URL normaliser still percent-encodes the parentheses.
	if got != `<a href="javascript:alert%281%29">x</a>` {
		t.Fatalf("template.URL should pass the scheme filter, got %s", got)
	}
}

func TestFirstExecuteEscapesOnlyTheTemplatesItReaches(t *testing.T) {
	tpl, err := template.New("root").Parse(`{{define "good"}}<p>{{.}}</p>{{end}}` +
		`{{define "bad"}}<a href="{{if .C}}/p/{{else}}/s?q={{end}}{{.X}}">x</a>{{end}}`)
	if err != nil {
		t.Fatal(err)
	}
	var sb strings.Builder
	if err := tpl.ExecuteTemplate(&sb, "good", "hi"); err != nil {
		t.Fatalf("the valid definition must run: %v", err)
	}
	// The ambiguous definition was never reached by that first execution; it fails on its own first run.
	err = tpl.ExecuteTemplate(&sb, "bad", map[string]any{"C": true, "X": "v"})
	var te *template.Error
	if !errors.As(err, &te) || te.ErrorCode != template.ErrAmbigContext {
		t.Fatalf("want ErrAmbigContext on first execution of the unrelated template, got %v", err)
	}
}

func TestOutputContextRecursiveTemplate(t *testing.T) {
	// A recursive template whose output context differs from its start context.
	// The error.go comment documents ErrOutputContext for this shape; its own example text
	// did not fail on Go 1.27.4, so this variant opens a tag attribute on every level.
	src := `{{define "t"}}{{if .}}<a href="{{template "t" .}}{{end}}{{end}}`
	tpl, err := template.New("x").Parse(src)
	if err != nil {
		t.Fatal(err)
	}
	var sb strings.Builder
	err = tpl.ExecuteTemplate(&sb, "t", nil)
	t.Logf("recursive variant: err=%v", err)
	// An ordinary, non-recursive partial may end in another context: the escaper propagates the computed context.
	ok, err := template.New("y").Parse(`{{define "open"}}<a href="{{end}}{{template "open"}}/x">z</a>`)
	if err != nil {
		t.Fatal(err)
	}
	sb.Reset()
	if err := ok.Execute(&sb, nil); err != nil {
		t.Fatalf("a non-recursive partial may end in a different context: %v", err)
	}
	t.Log(sb.String())
}

Typed strings: template.HTML and the trust boundary Must-know ​

In plain words: Sometimes a value already is HTML: a rendered Markdown post, a sanitised comment, an icon from your own code. Wrapping it in template.HTML tells the engine "I vouch for this, do not escape it". The engine believes you.

Common misunderstanding: "template.HTML(userInput) is the way to display user formatting." It is the way to create a stored XSS. The conversion is a trust boundary: everything on the left of it must be the output of a sanitiser (for example bluemonday) or a developer constant. The escaping test proves it: the same conversion applied to <img src=x onerror=alert(1)> leaves the payload in the page.

Definition: The types HTML, HTMLAttr, JS, JSStr, CSS, URL and Srcset (from content.go) "can carry safe content that is exempted from escaping". They are plain string types, so a conversion compiles without a word. Treat each as a grep target: every occurrence in a review is a question about where the string came from.

1  data := "<b>World</b>"
2  Execute("Hello, {{.}}!", data)                   ->  Hello, &lt;b&gt;World&lt;/b&gt;!
3  Execute("Hello, {{.}}!", template.HTML(data))    ->  Hello, <b>World</b>!
4  Execute("<a href=\"{{.}}\">", template.URL("javascript:alert(1)"))  ->  <a href="javascript:alert%281%29">   // scheme filter skipped, parentheses still percent-encoded: your promise, your bug
5  Execute("<a href=\"{{.}}\">", "javascript:alert(1)")                ->  <a href="#ZgotmplZ">

Real scenario: a CMS that stores sanitised HTML and renders it in a layout; a documentation site whose Markdown is converted at build time; a safeIcon("check") function in the FuncMap that returns an SVG constant; an admin tool that was "temporarily" given template.HTML for raw paste and never changed.

DoDo not
Return template.HTML from a FuncMap function that builds markup from constantsConvert request data directly
Sanitise on write or read with an allow-list library, then convertTrust "it came from our database" (the database holds what users sent)
Keep the conversion in one small package so it is auditableSpread conversions across handlers
Prefer template.URL only for schemes you listed (https, mailto)Pass user URLs as template.URL

Fix / how to use it: a safehtml.Render(md []byte) template.HTML helper that runs a sanitiser and returns the typed string; a vet-style grep -rn "template.HTML(" --include=*.go in CI that must match only that package.

Embedded templates: ParseFS with embed Must-know ​

In plain words: Put the template files in the binary with //go:embed, hand the resulting file system to ParseFS, and the program has no files to deploy and no paths to get wrong.

Common misunderstanding: "template.ParseGlob("templates/*.html") is fine because the process runs from the project directory." It runs from wherever systemd, Docker or the test runner starts it, and it parses the globs relative to that directory. ParseFS with embed removes the question. Another one: "ParseFS names the template after its path." It names it after the file's base name, so pages/home.gohtml and admin/home.gohtml clash (see name clashes).

Definition: template.ParseFS(fsys, patterns...) and (*Template).ParseFS arrived in Go 1.16 ("like ParseGlob, but read the templates from an fs.FS"). It "accepts a list of glob patterns" and fails when a pattern matches nothing. //go:embed patterns "may not contain ‘.’ or ‘..’ or empty path elements"; embedding a directory includes its files recursively "except that files with names beginning with ‘.’ or ‘_’ are excluded", unless the pattern starts with all:.

1  //go:embed templates                 var embedded embed.FS
2  fs.Sub(embedded, "templates")        -> an fs.FS rooted at the template directory (paths: "layouts/base.gohtml")
3  base.ParseFS(fsys, "layouts/*.gohtml", "partials/*.gohtml")   -> templates named "base.gohtml", "nav.gohtml", ...
4  fs.Glob(fsys, "pages/*.gohtml")      -> one file per page
5  fstest.MapFS{...}                    -> the same code under test, no disk

Real scenario: one static binary in a scratch container; the same renderer in tests against fstest.MapFS; in development against os.DirFS("render/templates") so edits show without a rebuild; a file named _partial.html that silently did not get embedded because of the leading underscore.

Source of the fs.FSWhenNote
embed.FS + fs.SubProductionImmutable, in the binary
os.DirFS("templates")DevelopmentCombine with dev-mode reload
fstest.MapFSUnit testsUsed by the render tests
fs.Sub(os.DirFS(...), "x")Plugins, themesSame call shape

Fix / how to use it: the render package embeds a templates directory, exposes it as FS(), and accepts any fs.FS in New. One consequence worth a test: a pattern that matches nothing is an error, so an empty partials directory breaks start-up (the test TestParseFSFailsWhenAPatternMatchesNothing shows the message).

go
// Package render parses an embedded template tree once, gives every page its
// own clone of the shared layout and partials, and renders into a buffer so
// that a failing template can still produce a clean 500.
package render

import (
	"bytes"
	"embed"
	"fmt"
	"html/template"
	"io/fs"
	"net/http"
	"path"
	"strings"
	"sync"
)

//go:embed templates
var embedded embed.FS

// FS returns the embedded template tree rooted at "templates".
func FS() fs.FS {
	sub, err := fs.Sub(embedded, "templates")
	if err != nil {
		panic(err) // the directory is embedded at build time; cannot fail at run time
	}
	return sub
}

// Flash is a one-shot message shown on the next page.
type Flash struct {
	Level string // "success", "error", "info"
	Text  string
}

// Page is the dot that every layout receives.
type Page struct {
	Nonce string // CSP nonce for inline scripts
	CSRF  string // hidden form token
	Flash *Flash
	Data  any // page-specific data
}

// Renderer holds one template set per page.
type Renderer struct {
	fsys  fs.FS
	funcs template.FuncMap
	dev   bool

	pages map[string]*template.Template // written once in New, read-only afterwards: no lock
}

// New parses the tree. With dev set, templates are re-read on every call so a
// browser refresh shows edits; without it a parse error stops the program at
// start-up instead of during the first request.
func New(fsys fs.FS, funcs template.FuncMap, dev bool) (*Renderer, error) {
	r := &Renderer{fsys: fsys, funcs: funcs, dev: dev}
	pages, err := r.parse()
	if err != nil {
		return nil, err
	}
	r.pages = pages
	return r, nil
}

// parse builds the shared base once and clones it for each page file.
func (r *Renderer) parse() (map[string]*template.Template, error) {
	base, err := template.New("").Funcs(r.funcs).ParseFS(r.fsys, "layouts/*.gohtml", "partials/*.gohtml")
	if err != nil {
		return nil, fmt.Errorf("render: parse shared templates: %w", err)
	}
	files, err := fs.Glob(r.fsys, "pages/*.gohtml")
	if err != nil {
		return nil, err
	}
	pages := make(map[string]*template.Template, len(files))
	for _, f := range files {
		t, err := base.Clone()
		if err != nil {
			return nil, fmt.Errorf("render: clone base for %s: %w", f, err)
		}
		if _, err := t.ParseFS(r.fsys, f); err != nil {
			return nil, fmt.Errorf("render: parse %s: %w", f, err)
		}
		pages[strings.TrimSuffix(path.Base(f), ".gohtml")] = t
	}
	return pages, nil
}

func (r *Renderer) lookup(page string) (*template.Template, error) {
	if r.dev {
		pages, err := r.parse()
		if err != nil {
			return nil, err
		}
		t, ok := pages[page]
		if !ok {
			return nil, fmt.Errorf("render: no page %q", page)
		}
		return t, nil
	}
	t, ok := r.pages[page]
	if !ok {
		return nil, fmt.Errorf("render: no page %q", page)
	}
	return t, nil
}

var bufPool = sync.Pool{New: func() any { return new(bytes.Buffer) }}

// Render executes the "base" layout for page into a buffer. Only when that
// succeeds are the headers sent, so an error leaves the ResponseWriter
// untouched and the caller can still answer 500.
func (r *Renderer) Render(w http.ResponseWriter, status int, page string, data any) error {
	return r.execute(w, status, page, "base", data)
}

// RenderBlock executes one named template of a page, for example the list
// fragment an htmx request asks for, without the layout around it.
func (r *Renderer) RenderBlock(w http.ResponseWriter, status int, page, block string, data any) error {
	return r.execute(w, status, page, block, data)
}

func (r *Renderer) execute(w http.ResponseWriter, status int, page, name string, data any) error {
	t, err := r.lookup(page)
	if err != nil {
		return err
	}
	buf := bufPool.Get().(*bytes.Buffer)
	buf.Reset()
	defer func() {
		if buf.Cap() <= 64<<10 { // do not keep one huge page alive in the pool
			bufPool.Put(buf)
		}
	}()
	if err := t.ExecuteTemplate(buf, name, data); err != nil {
		return fmt.Errorf("render %s/%s: %w", page, name, err)
	}
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	w.WriteHeader(status)
	_, err = buf.WriteTo(w)
	return err
}

Template inheritance: define, block, template Must-know ​

In plain words: A layout is a template with holes. block "content" marks a hole and gives it default content; a page fills it by defining a template with the same name. template "nav" . calls another template and passes it data. That is all "inheritance" is in Go: named templates and one-way calls.

Common misunderstanding: "block and template are the same thing." template calls a template that must exist; block defines the template (with default content) and calls it in one step, so a page may override it. The text/template doc says it directly: "A block is shorthand for defining a template ... and then executing it in place. The typical use is to define a set of root templates that are then customized by redefining the block templates within." The other trap: template "nav" without the dot gives nav a nil dot, not the caller's.

Definition: {{ define "name" }}...{{ end }} names a template (top-level only); {{ template "name" pipeline }} runs it with dot set to the pipeline's value; {{ block "name" pipeline }}default{{ end }} does both. Definitions in later Parse calls replace earlier ones of the same name until the set is first executed.

1  base.gohtml        {{define "base"}}...<title>{{block "title" .}}Shop{{end}}</title>...{{template "nav" .}}...{{block "content" .}}default{{end}}{{end}}
2  home.gohtml        {{define "title"}}Home{{end}}  {{define "content"}}<h1>Welcome</h1>{{end}}
3  contact.gohtml     {{define "content"}}<form>...</form>{{end}}      (title falls back to "Shop")
4  Execute(w, "base", data) on the home clone     -> Home / Welcome
5  Execute(w, "base", data) on the contact clone  -> Shop / the form

Real scenario: an admin area with its own layout that reuses the same partials; a print layout that swaps only the content block; an error page that overrides title and keeps everything else; a layout block "scripts" that individual pages extend.

DirectiveNeeds a definition?Default contentTypical use
template "x" .Yes: an error if it does not exist (ErrNoSuchTemplate when the escaper finds out first)NoPartials
block "x" .NoYesLayout holes
define "x"(it is the definition)n/aPage overrides, partials
Lookup("x")Returns nil if missingn/aTests, optional templates
Parse the shared parts once, clone the set for every pagelayouts/base.gohtmldefine "base"block "title" / block "content"template "nav" / template "flash"partials/*.gohtmldefine "nav", "flash", "field"called with template and dictpages/*.gohtmleach file: define "title",define "content" (same names!)base set (ParseFS layouts + partials, Funcs first)built once at start-up, never executed itselfhomebase clone +home.gohtmlcontactbase clone +contact.gohtmlitemsbase clone +items.gohtmlClone()Clone()Clone()Shared set instead of cloneslast Parse of "content" winsExecute any clone with ExecuteTemplate(w, "base", data). Clone must happen before the base set is executed once.Dashed: parsing every page into ONE set makes the pages overwrite each other, silently.

Fix / how to use it: the layout and partials in the render package, each page with only define blocks. The inherit snippet isolates the mechanism in strings so you can read it in one screen.

html
{{define "base"}}<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="htmx-config" content='{"includeIndicatorStyles":false}'>
<title>{{block "title" .}}Shop{{end}} - Demo</title>
<link rel="stylesheet" href="{{asset "app.css"}}">
</head>
<body hx-headers='{"X-CSRF-Token": "{{.CSRF}}"}'>
{{template "nav" .}}
{{template "flash" .Flash}}
<main>
{{block "content" .}}<p>Nothing here yet.</p>{{end}}
</main>
<script nonce="{{.Nonce}}">document.documentElement.classList.add("js");</script>
<script nonce="{{.Nonce}}" src="{{asset "htmx.min.js"}}"></script>
<script nonce="{{.Nonce}}" src="{{asset "app.js"}}"></script>
</body>
</html>
{{end}}
html
{{define "title"}}Contact{{end}}
{{define "content" -}}
<h1>Contact us</h1>
<form method="post" action="/contact" novalidate>
  <input type="hidden" name="csrf_token" value="{{.CSRF}}">
  {{template "field" dict "Name" "email" "Label" "Email" "Type" "email" "Value" (.Data.Value "email") "Error" (.Data.Error "email")}}
  {{template "field" dict "Name" "message" "Label" "Message" "Type" "text" "Value" (.Data.Value "message") "Error" (.Data.Error "message")}}
  <button type="submit">Send</button>
</form>
{{- end}}
go
// Package inherit shows template inheritance with define/block/template and
// the name clash that appears when every page defines the same block names.
package inherit

import (
	"bytes"
	"fmt"
	"html/template"
)

// The layout declares two blocks with default content and includes a partial.
const layout = `{{define "base"}}<html><head><title>{{block "title" .}}Site{{end}}</title></head>
<body>{{template "nav" .}}{{block "content" .}}<p>default content</p>{{end}}</body></html>{{end}}`

// nav is a partial: a named template without a layout of its own.
const nav = `{{define "nav"}}<nav>{{.User}}</nav>{{end}}`

// Pages override the blocks and nothing else.
var pages = map[string]string{
	"home":  `{{define "title"}}Home{{end}}{{define "content"}}<h1>Home for {{.User}}</h1>{{end}}`,
	"about": `{{define "title"}}About{{end}}{{define "content"}}<h1>About us</h1>{{end}}`,
	"bare":  ``, // overrides nothing: the block defaults show through
}

// Data is the dot for every page.
type Data struct{ User string }

// Shared parses the layout and every page into ONE template set. All pages
// define "content", so the last definition silently replaces the others.
func Shared() (*template.Template, error) {
	root := template.New("")
	for _, src := range []string{layout, nav, pages["home"], pages["about"]} {
		if _, err := root.Parse(src); err != nil {
			return nil, err
		}
	}
	return root, nil
}

// PerPage parses the shared parts once and gives every page its own clone,
// so a page can define "content" without touching the others.
func PerPage() (map[string]*template.Template, error) {
	base, err := template.New("").Parse(layout)
	if err != nil {
		return nil, err
	}
	if _, err := base.Parse(nav); err != nil {
		return nil, err
	}
	out := make(map[string]*template.Template, len(pages))
	for name, src := range pages {
		t, err := base.Clone() // must happen before base is ever executed
		if err != nil {
			return nil, fmt.Errorf("clone for %s: %w", name, err)
		}
		if _, err := t.Parse(src); err != nil {
			return nil, fmt.Errorf("page %s: %w", name, err)
		}
		out[name] = t
	}
	return out, nil
}

// Render executes the "base" template of t.
func Render(t *template.Template, d Data) (string, error) {
	var buf bytes.Buffer
	if err := t.ExecuteTemplate(&buf, "base", d); err != nil {
		return "", err
	}
	return buf.String(), nil
}
go
package inherit

import (
	"strings"
	"testing"
)

func TestSharedSetNameClash(t *testing.T) {
	set, err := Shared()
	if err != nil {
		t.Fatal(err)
	}
	got, err := Render(set, Data{User: "ann"})
	if err != nil {
		t.Fatal(err)
	}
	// "home" was parsed first, "about" last: about's definitions win.
	if !strings.Contains(got, "<h1>About us</h1>") || strings.Contains(got, "Home for") {
		t.Fatalf("expected the last page to win the name clash:\n%s", got)
	}
	t.Log(got)
}

func TestPerPageClones(t *testing.T) {
	set, err := PerPage()
	if err != nil {
		t.Fatal(err)
	}
	cases := map[string][]string{
		"home":  {"<title>Home</title>", "<h1>Home for ann</h1>", "<nav>ann</nav>"},
		"about": {"<title>About</title>", "<h1>About us</h1>"},
		"bare":  {"<title>Site</title>", "<p>default content</p>"}, // block defaults
	}
	for name, wants := range cases {
		got, err := Render(set[name], Data{User: "ann"})
		if err != nil {
			t.Fatalf("%s: %v", name, err)
		}
		for _, w := range wants {
			if !strings.Contains(got, w) {
				t.Errorf("%s: missing %q in\n%s", name, w, got)
			}
		}
	}
}

func TestCloneAfterExecuteFails(t *testing.T) {
	set, err := PerPage()
	if err != nil {
		t.Fatal(err)
	}
	if _, err := Render(set["home"], Data{}); err != nil {
		t.Fatal(err)
	}
	if _, err := set["home"].Clone(); err == nil {
		t.Fatal("Clone after Execute must fail")
	} else {
		t.Log(err)
	}
}

Layouts, partials, template sets and name clashes Must-know ​

In plain words: All templates parsed into one *Template share one namespace: a flat dictionary from name to template. Two pages that both define "content" cannot live in the same dictionary; the second Parse silently replaces the first. The cure is one dictionary per page, built by cloning the shared part.

Common misunderstanding: "ParseGlob("pages/*.html") gives me one template per page." It gives you one set containing every file, and every page's define "content" fights for the same name. With a layout that calls block "content", the last file parsed wins for every page; the site renders the about page at / and nothing reports an error.

Definition: A template set ("name space of associated templates") is the transitive closure of associations; New(name) on an existing template adds to the same set. Clone "returns a duplicate of the template, including all associated templates ... further calls to Parse in the copy will add templates to the copy but not to the original". It "returns an error if t has already been executed".

1  base  := New("").ParseFS(layouts, partials)         set: {base, nav, flash, field}
2  home  := base.Clone(); home.ParseFS(pages/home)     set: {base, nav, flash, field, title, content}  (home's)
3  about := base.Clone(); about.ParseFS(pages/about)   set: {... title, content}                       (about's)
4  home.Execute("base")   -> home content      about.Execute("base") -> about content
5  -- shared set instead of clones --
6  all := New("").ParseFS(layouts, partials, pages)    "content" defined twice -> the last parsed file wins
7  all.Execute("base")    -> same page for every URL

Real scenario: a developer adds pages/pricing.gohtml with define "content" and the home page changes to the pricing page; a partial named form in partials/ and again in a page; two modules each shipping an index.html into the same set; ParseFS names by base name, so admin/index.gohtml and public/index.gohtml clash even in different directories.

Layout of the setName clashesCostVerdict
One set for everythingYes, between pagesLowest memoryOnly if pages never share a block name
One clone per pageNo (each page has its own namespace)Shared partials are duplicated as treesThe usual answer
One set per page, parsed from scratchNoSlow start-up, repeated parsing of layoutUnnecessary
Unique names (home-content, about-content)No, by disciplineLowestWorks but defeats block

Fix / how to use it: the render.parse function: parse layouts and partials once into base, then for each file in pages/ clone base and parse just that file. Call Funcs before the first parse (a template that names an unknown function fails to parse) and clone before anything executes. The inherit test TestSharedSetNameClash makes the failure visible: it asserts that the last page wins.

Caching: parse once, Clone, dev-mode reload Must-know ​

In plain words: Parsing and escaping are work you do once, at start-up. Per request you only execute. In development you want the opposite: edit a file, press refresh, see it. One flag switches between the two.

Common misunderstanding: "A cache of parsed templates needs a lock." A *template.Template that has been fully built can be executed from many goroutines at once: the documentation promises that "a template may be executed safely in parallel, although if parallel executions share a Writer the output may be interleaved". Only building (Parse, Funcs, Clone, AddParseTree) needs to happen before sharing. The other trap: escaping happens lazily, at the first Execute, which then freezes the set; later Parse fails with "html/template: cannot Parse after Execute".

Definition: Production: New parses everything, returns the first error (so a typo stops the process before it listens), and stores one set per page in a map that is read-only afterwards. Development: lookup re-runs the parse on every call from os.DirFS, so a changed file is picked up with no restart and an error shows up in the browser instead of at boot.

1  start-up (prod)    New(embedFS, funcs, dev=false)  -> parse layouts+partials once -> Clone+Parse per page -> pages["home"] ...
2  request            lookup("home") -> map read, no lock -> ExecuteTemplate(buf, "base", data)         // no parsing
3  first Execute      escaper runs on the page's tree, set frozen                                    // once per page
4  start-up (dev)     New(os.DirFS("render/templates"), funcs, dev=true)
5  request (dev)      lookup("home") -> parse everything again (about 80 us here) -> Execute         // edits visible
6  edit base.gohtml   next request re-parses: no restart, no file watcher

Real scenario: a handler that calls template.ParseFiles per request and shows 80 µs of parsing before 7 µs of rendering (see the lab); an application that worked in dev (reload) and fails at boot in production because a template has a typo, which is the better failure; a file-watcher setup (reflex watches a directory and reruns a command) that restarts the server on every template save when a dev flag would do.

StrategyPer-request costEdit visibleBoot behaviour
Parse per requestHigh (parse + escape every time)ImmediatelyErrors on the first request
Parse once at start-upExecute onlyAfter restartParse errors stop the process
Parse once + dev reload from os.DirFSExecute only in prod, parse in devImmediately in devBoth, chosen by a flag
Lazy parse on first use, cache in a sync.MapExecute after first hitAfter restartErrors on first hit of that page

Fix / how to use it: the Renderer.dev flag. app.New(key, devTemplates, log) takes a directory: when it is non-empty (the lab main sets it from APP_ENV=dev) templates come from os.DirFS(devTemplates) and dev=true; when it is empty production uses render.FS() and dev=false. The app test TestDevModeReloadsTemplatesFromDisk copies the tree to a temp directory, edits a file on disk and sees the change on the next request. The map is written once in New and only read afterwards, so no lock is needed; dev mode never touches it (it re-parses into a fresh map per call).

go
package render

import (
	"html/template"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
	"testing/fstest"
	"time"

	"academy/templates-server-rendering/forms"
	"academy/templates-server-rendering/funcs"
)

func testFuncs() template.FuncMap {
	m := funcs.Map()
	m["asset"] = func(name string) string { return "/static/" + name }
	return m
}

type item struct {
	Name  string
	Qty   int
	Cents int64
}

type itemsData struct {
	Items []item
	Next  int
}

func newRenderer(t testing.TB) *Renderer {
	t.Helper()
	r, err := New(FS(), testFuncs(), false)
	if err != nil {
		t.Fatal(err)
	}
	return r
}

func TestHomePageUsesLayoutAndPartials(t *testing.T) {
	r := newRenderer(t)
	rec := httptest.NewRecorder()
	err := r.Render(rec, http.StatusOK, "home", Page{Nonce: "n0nce", Data: time.Date(2026, 11, 28, 0, 0, 0, 0, time.UTC)})
	if err != nil {
		t.Fatal(err)
	}
	body := rec.Body.String()
	for _, want := range []string{
		"<title>Home - Demo</title>", // block "title" overridden by the page
		`<a href="/items">Items</a>`, // partial "nav"
		"Rendered by html/template at 2026-11-28.",
		`<script nonce="n0nce">`,
	} {
		if !strings.Contains(body, want) {
			t.Errorf("missing %q in\n%s", want, body)
		}
	}
	if ct := rec.Header().Get("Content-Type"); ct != "text/html; charset=utf-8" {
		t.Errorf("Content-Type = %q", ct)
	}
}

func TestEachPageHasItsOwnContentBlock(t *testing.T) {
	r := newRenderer(t)
	home := httptest.NewRecorder()
	contact := httptest.NewRecorder()
	if err := r.Render(home, 200, "home", Page{Data: time.Time{}}); err != nil {
		t.Fatal(err)
	}
	if err := r.Render(contact, 200, "contact", Page{CSRF: "tok", Data: forms.New(nil)}); err != nil {
		t.Fatal(err)
	}
	if strings.Contains(home.Body.String(), "Contact us") || strings.Contains(contact.Body.String(), "Welcome") {
		t.Fatal("pages bled into each other: block names clashed")
	}
	if !strings.Contains(contact.Body.String(), `name="csrf_token" value="tok"`) {
		t.Fatalf("csrf field missing:\n%s", contact.Body)
	}
}

func TestFormErrorsAndStickyValues(t *testing.T) {
	r := newRenderer(t)
	f := forms.New(map[string][]string{"email": {`"><script>x</script>`}})
	f.Email("email")
	f.Required("message")
	rec := httptest.NewRecorder()
	if err := r.Render(rec, http.StatusUnprocessableEntity, "contact", Page{Data: f}); err != nil {
		t.Fatal(err)
	}
	body := rec.Body.String()
	if rec.Code != http.StatusUnprocessableEntity {
		t.Errorf("status = %d", rec.Code)
	}
	if strings.Contains(body, "<script>x") {
		t.Errorf("sticky value was not escaped:\n%s", body)
	}
	for _, want := range []string{`class="field has-error"`, `<span class="error">Enter a valid email address</span>`, `<span class="error">This field is required</span>`} {
		if !strings.Contains(body, want) {
			t.Errorf("missing %q in\n%s", want, body)
		}
	}
}

func TestFlashPartial(t *testing.T) {
	r := newRenderer(t)
	with, without := httptest.NewRecorder(), httptest.NewRecorder()
	_ = r.Render(with, 200, "home", Page{Flash: &Flash{Level: "success", Text: "Saved <b>"}, Data: time.Time{}})
	_ = r.Render(without, 200, "home", Page{Data: time.Time{}})
	if !strings.Contains(with.Body.String(), `<div class="flash flash-success" role="status">Saved &lt;b&gt;</div>`) {
		t.Errorf("flash not rendered:\n%s", with.Body)
	}
	if strings.Contains(without.Body.String(), "flash-") {
		t.Error("flash div must not appear without a message")
	}
}

func TestRenderBlockForHTMXFragment(t *testing.T) {
	r := newRenderer(t)
	rec := httptest.NewRecorder()
	data := itemsData{Items: []item{{"pen", 1, 250}, {"ink", 3, 1999}}, Next: 2}
	if err := r.RenderBlock(rec, 200, "items", "item-list", data); err != nil {
		t.Fatal(err)
	}
	body := rec.Body.String()
	if strings.Contains(body, "<html") || strings.Contains(body, "<nav>") {
		t.Fatalf("fragment must not contain the layout:\n%s", body)
	}
	for _, want := range []string{"pen: 1 unit at 2.50", "ink: 3 units at 19.99"} {
		if !strings.Contains(body, want) {
			t.Errorf("missing %q in\n%s", want, body)
		}
	}
	empty := httptest.NewRecorder()
	_ = r.RenderBlock(empty, 200, "items", "item-list", itemsData{})
	if !strings.Contains(empty.Body.String(), "No items.") {
		t.Errorf("range/else branch missing:\n%s", empty.Body)
	}
}

func TestExecutionErrorLeavesResponseUntouched(t *testing.T) {
	fsys := fstest.MapFS{
		"layouts/base.gohtml": {Data: []byte(`{{define "base"}}<html><body>top{{.Data.Missing.Deep}}bottom</body></html>{{end}}`)},
		"partials/p.gohtml":   {Data: []byte(`{{define "p"}}{{end}}`)},
		"pages/broken.gohtml": {Data: []byte(`{{define "x"}}x{{end}}`)},
	}
	r, err := New(fsys, testFuncs(), false)
	if err != nil {
		t.Fatal(err)
	}
	rec := httptest.NewRecorder()
	err = r.Render(rec, http.StatusOK, "broken", Page{Data: map[string]any{"Missing": (*int)(nil)}})
	if err == nil {
		t.Fatal("expected an execution error")
	}
	t.Log(err)
	if rec.Body.Len() != 0 || rec.Header().Get("Content-Type") != "" {
		t.Fatalf("nothing may be written before the buffer succeeds; body=%q", rec.Body)
	}
	// The caller is still free to send a proper 500.
	http.Error(rec, "Internal Server Error", http.StatusInternalServerError)
	if rec.Code != 500 {
		t.Fatalf("status = %d", rec.Code)
	}
}

func TestUnknownPageIsAnError(t *testing.T) {
	r := newRenderer(t)
	if err := r.Render(httptest.NewRecorder(), 200, "nope", Page{}); err == nil {
		t.Fatal("expected error")
	}
}

func TestParseErrorFailsAtStartup(t *testing.T) {
	fsys := fstest.MapFS{
		"layouts/base.gohtml": {Data: []byte(`{{define "base"}}{{if}}{{end}}`)},
		"partials/p.gohtml":   {Data: []byte(`{{define "p"}}{{end}}`)},
	}
	if _, err := New(fsys, testFuncs(), false); err == nil {
		t.Fatal("a broken template must stop start-up")
	} else {
		t.Log(err)
	}
}

func TestDevModeReloadsProductionModeDoesNot(t *testing.T) {
	mk := func(text string) fstest.MapFS {
		return fstest.MapFS{
			"layouts/base.gohtml": {Data: []byte(`{{define "base"}}{{template "body" .}}{{end}}`)},
			"partials/p.gohtml":   {Data: []byte(`{{define "p"}}{{end}}`)},
			"pages/p.gohtml":      {Data: []byte(`{{define "body"}}` + text + `{{end}}`)},
		}
	}
	for _, dev := range []bool{true, false} {
		fsys := mk("v1")
		r, err := New(fsys, testFuncs(), dev)
		if err != nil {
			t.Fatal(err)
		}
		fsys["pages/p.gohtml"] = &fstest.MapFile{Data: []byte(`{{define "body"}}v2{{end}}`)}
		rec := httptest.NewRecorder()
		if err := r.Render(rec, 200, "p", Page{}); err != nil {
			t.Fatal(err)
		}
		want := map[bool]string{true: "v2", false: "v1"}[dev]
		if rec.Body.String() != want {
			t.Errorf("dev=%v: got %q want %q", dev, rec.Body.String(), want)
		}
	}
}

func BenchmarkRenderCached(b *testing.B) {
	r := newRenderer(b)
	data := Page{Nonce: "n", Data: itemsData{Items: []item{{"pen", 1, 250}, {"ink", 3, 1999}}, Next: 2}}
	b.ReportAllocs()
	for b.Loop() {
		if err := r.Render(httptest.NewRecorder(), 200, "items", data); err != nil {
			b.Fatal(err)
		}
	}
}

func BenchmarkRenderParseEveryRequest(b *testing.B) {
	data := Page{Nonce: "n", Data: itemsData{Items: []item{{"pen", 1, 250}, {"ink", 3, 1999}}, Next: 2}}
	b.ReportAllocs()
	for b.Loop() {
		r, err := New(FS(), testFuncs(), false) // what a handler does when it calls ParseFiles per request
		if err != nil {
			b.Fatal(err)
		}
		if err := r.Render(httptest.NewRecorder(), 200, "items", data); err != nil {
			b.Fatal(err)
		}
	}
}

func TestParseFSFailsWhenAPatternMatchesNothing(t *testing.T) {
	fsys := fstest.MapFS{"layouts/base.gohtml": {Data: []byte(`{{define "base"}}{{end}}`)}}
	_, err := New(fsys, testFuncs(), false)
	if err == nil {
		t.Fatal("ParseFS must fail when a glob matches no file")
	}
	t.Log(err)
}

Passing data: structs, maps, dot and $ Must-know ​

In plain words: Dot (.) is "the current value". At the top it is whatever you passed to Execute; inside range and with it becomes the element or the value; template "x" . passes it on. $ always means the value you started with.

Common misunderstanding: "I passed a struct, so .Name calls a getter." Dot access reads an exported field or calls an exported method (.Name, .Format "2006"), or reads a map key (.Tags.gift). Unexported fields cannot be read: the error is name is an unexported field of struct type T, and a field that does not exist gives can't evaluate field name in type T. Another one: inside range, . is the element, so .Title of the outer page is gone; use $.Title.

Definition: Pass one value. Structs are checked at run time (a missing field is an execution error); a missing map key prints as an empty string in html/template (text/template prints <no value>), unless Option("missingkey=error") is set (the option arrived in Go 1.5), which stops execution with map has no entry for key "nope". A nil pointer in the path is an execution error: nil pointer evaluating ....

1  type Page struct { Title string; User *User; Items []Item; Flash *Flash }
2  {{.Title}}                         field
3  {{.User.Name}}                     nested field; error if .User is nil -> guard with {{with .User}}
4  {{range .Items}}{{.Name}} of {{$.Title}}{{end}}   dot = element, $ = Page
5  {{index .Tags "gift"}}             map key with a dynamic or awkward name
6  {{.Date.Format "2006-01-02"}}      method call with an argument
7  {{template "item" .}}              pass dot on;  {{template "item"}} would pass nil

Real scenario: a Page struct with Data any for the page-specific part; a map[string]any for a one-off partial; a method func (o Order) Total() int64 called from the template; a typo .Titel that fails the first test run, which is a reason to render every page in a test.

Data shapeAccessTypo behaviourGood for
Struct.Field, .Method argExecution errorPages (typed, discoverable)
map[string]any.key, index . "key"Empty string (or an error with missingkey=error)One-off partials, dict
Slicerange, index .L 0, lenindex out of range is an errorLists
any holding a structSame as the structSamePage.Data
nilPrints nothingn/aOptional values behind with

Fix / how to use it: one page struct per view (render.Page carries Nonce, CSRF, Flash, Data), the specific data in Data, and a test per page that renders it with a realistic value so a typo cannot reach production.

Actions and pipelines: range, with, if, else with Must-know ​

In plain words: if chooses, range repeats, with narrows. A pipeline passes the result of the left side as the last argument of the right side.

Common misunderstanding: "if tests for nil." It tests truthiness: false, 0, a nil pointer, a nil interface, an empty array, slice, map or string are all false. So {{ if .Count }} hides a zero, which is often a bug (a legitimate "0 items" disappears). Also: and and or are functions that return one of their arguments, not booleans, and eq evaluates all its arguments (no short circuit).

Definition: from the text/template documentation: if runs when the value is not empty; range iterates an array, slice, map, channel, and since Go 1.24 an integer or a function iterator, with else for the empty case; with rebinds dot when the value is non-empty, and since Go 1.23 supports else with for a second candidate. break and continue work inside range. A pipeline is a | f | g, which means g (f a).

1  {{range .Items}}<li>{{.Name}}</li>{{else}}<li>No items.</li>{{end}}
2  {{with .Comment}}<p>{{.}}</p>{{else with .Status}}<p>status {{.}}</p>{{else}}none{{end}}     // 1.23
3  {{range 3}}{{.}} {{end}}                                                                      // 1.24: 0 1 2
4  {{range $i, $e := .Items}}{{$i}}: {{$e.Name}}{{end}}
5  {{.Total | money | printf "EUR %s"}}                                  // printf gets money's result as its last argument
6  {{if and .User (not .User.Banned)}}...{{end}}                         // and/or return an argument, not a bool

Real scenario: an empty-state message in a table; an "edit" link shown only when the user is an owner; a pager that needs the index; a banner chosen from one of three optional fields with else with; a count that must show 0.

FormDot insideEmpty branchAdded in
if xunchangedelsealways
range xthe element (a map yields its values in key order)elsealways
range N (integer)the counter 0..N-1elseGo 1.24
range f (iterator function)yielded valueselseGo 1.24
with xxelsealways
with x ... else with yy in the second branchfinal elseGo 1.23
break, continue (inside range)n/an/aGo 1.18

Fix / how to use it: the funcs tests exercise each form with assertions, including the zero-versus-empty trap and $ inside range.

go
package funcs

import (
	"bytes"
	"html/template"
	"strings"
	"testing"
	"time"
)

func run(t *testing.T, src string, data any) string {
	t.Helper()
	tpl, err := template.New("t").Funcs(Map()).Parse(src)
	if err != nil {
		t.Fatal(err)
	}
	var buf bytes.Buffer
	if err := tpl.Execute(&buf, data); err != nil {
		t.Fatal(err)
	}
	return buf.String()
}

type order struct {
	ID      int
	Status  string
	Total   int64
	Paid    time.Time
	Lines   []string
	Tags    map[string]string
	Comment *string
}

func TestComparisonsPrintfIndexPipelines(t *testing.T) {
	o := order{ID: 7, Status: "paid", Total: 12345, Lines: []string{"pen", "ink"}, Tags: map[string]string{"gift": "yes"}}
	cases := []struct{ name, src, want string }{
		{"eq many", `{{if eq .Status "new" "paid"}}ok{{end}}`, "ok"},
		{"lt and", `{{if and (gt .ID 5) (lt .ID 10)}}mid{{end}}`, "mid"},
		{"not", `{{if not .Comment}}none{{end}}`, "none"},
		{"printf", `{{printf "%05d|%-6s|" .ID .Status}}`, "00007|paid  |"},
		{"index slice", `{{index .Lines 1}}`, "ink"},
		{"index map", `{{index .Tags "gift"}}`, "yes"},
		{"index missing key", `[{{index .Tags "none"}}]`, "[]"},
		{"pipeline", `{{.Total | money | printf "EUR %s"}}`, "EUR 123.45"},
		{"len", `{{len .Lines}} {{plural (len .Lines) "line" "lines"}}`, "2 lines"},
		{"date zero", `{{date .Paid}}`, "never"},
	}
	for _, c := range cases {
		if got := run(t, c.src, o); got != c.want {
			t.Errorf("%s: got %q want %q", c.name, got, c.want)
		}
	}
}

func TestRangeWithElse(t *testing.T) {
	src := `{{range .Lines}}[{{.}}]{{else}}empty{{end}}`
	if got := run(t, src, order{Lines: []string{"a", "b"}}); got != "[a][b]" {
		t.Errorf("got %q", got)
	}
	if got := run(t, src, order{}); got != "empty" {
		t.Errorf("got %q", got)
	}
	// Go 1.23: "else with"
	src = `{{with .Comment}}c{{else with .Status}}s={{.}}{{else}}none{{end}}`
	if got := run(t, src, order{Status: "new"}); got != "s=new" {
		t.Errorf("else with: got %q", got)
	}
	// Go 1.24: range over an integer
	if got := run(t, `{{range 3}}{{.}}{{end}}`, nil); got != "012" {
		t.Errorf("range int: got %q", got)
	}
	// Dot inside range is the element; the outer value needs $.
	src = `{{range .Lines}}{{$.ID}}:{{.}} {{end}}`
	if got := run(t, src, order{ID: 3, Lines: []string{"x", "y"}}); got != "3:x 3:y " {
		t.Errorf("dollar: got %q", got)
	}
}

func TestWhitespaceControl(t *testing.T) {
	loose := "a\n{{if true}}\nb\n{{end}}\nc"
	tight := "a\n{{- if true}}\nb\n{{- end}}\nc"
	if got := run(t, loose, nil); got != "a\n\nb\n\nc" {
		t.Errorf("loose: got %q", got)
	}
	if got := run(t, tight, nil); got != "a\nb\nc" {
		t.Errorf("tight: got %q", got)
	}
	// "{{-3}}" is the number -3, not a trim marker.
	if got := run(t, "x {{-3}} y", nil); got != "x -3 y" {
		t.Errorf("minus: got %q", got)
	}
	// "{{- 3}}" trims the text before it.
	if got := run(t, "x {{- 3}} y", nil); got != "x3 y" {
		t.Errorf("trim before: got %q", got)
	}
}

func TestNestedTemplateWithDict(t *testing.T) {
	src := `{{define "field"}}<label for="{{.Name}}">{{.Label}}</label><input name="{{.Name}}" value="{{.Value}}">{{with .Error}}<em>{{.}}</em>{{end}}{{end}}` +
		`{{template "field" dict "Name" "email" "Label" "Email" "Value" .Email "Error" .EmailErr}}`
	got := run(t, src, map[string]string{"Email": `a"b@x.test`, "EmailErr": "invalid"})
	want := `<label for="email">Email</label><input name="email" value="a&#34;b@x.test"><em>invalid</em>`
	if got != want {
		t.Errorf("got  %s\nwant %s", got, want)
	}
}

func TestDotDoesNotLeakIntoCalledTemplate(t *testing.T) {
	tpl, err := template.New("t").Parse(`{{define "inner"}}[{{.}}]{{end}}{{template "inner"}}|{{template "inner" .}}`)
	if err != nil {
		t.Fatal(err)
	}
	var sb strings.Builder
	if err := tpl.Execute(&sb, "outer"); err != nil {
		t.Fatal(err)
	}
	if sb.String() != "[]|[outer]" { // no argument means dot is nil inside
		t.Errorf("got %q", sb.String())
	}
}

func TestDictErrors(t *testing.T) {
	if _, err := Dict("a"); err == nil {
		t.Error("odd args must fail")
	}
	if _, err := Dict(1, 2); err == nil {
		t.Error("non-string key must fail")
	}
}

func TestUnknownFunctionFailsAtParse(t *testing.T) {
	_, err := template.New("t").Parse(`{{upper .}}`)
	if err == nil {
		t.Fatal("parse must fail when the function is not registered yet")
	}
	t.Log(err)
}

func TestMoney(t *testing.T) {
	for in, want := range map[int64]string{0: "0.00", 5: "0.05", 12345: "123.45", -250: "-2.50"} {
		if got := Money(in); got != want {
			t.Errorf("Money(%d)=%s want %s", in, got, want)
		}
	}
}

func TestMissingMapKeyBehaviour(t *testing.T) {
	m := map[string]any{"a": 1}
	// html/template: a missing key renders as an empty string by default.
	if got := run(t, `[{{.nope}}]`, m); got != "[]" {
		t.Errorf("default: got %q", got)
	}
	// text/template would print "<no value>"; the option makes execution fail in both packages.
	tpl, err := template.New("t").Option("missingkey=error").Parse(`[{{.nope}}]`)
	if err != nil {
		t.Fatal(err)
	}
	var sb strings.Builder
	if err := tpl.Execute(&sb, m); err == nil {
		t.Error("missingkey=error must fail")
	} else {
		t.Log(err)
	}
}

type pageWithFunc struct {
	T func(key string, n int) string
}

func TestFunctionValuedFieldNeedsCall(t *testing.T) {
	d := pageWithFunc{T: func(k string, n int) string { return k + "#" + Money(int64(n)) }}
	tpl, err := template.New("t").Parse(`{{.T "cart" 3}}`)
	if err != nil {
		t.Fatal(err)
	}
	var sb strings.Builder
	if err := tpl.Execute(&sb, d); err == nil {
		t.Fatal("a function-valued field is not a method: execution must fail")
	} else {
		t.Log(err)
	}
	if got := run(t, `{{call .T "cart" 3}}`, d); got != "cart#0.03" {
		t.Errorf("call: got %q", got)
	}
}

Functions: FuncMap, comparison functions, printf, index Must-know ​

In plain words: A template can only call functions you register, plus a small built-in set. Registration is a map[string]any; each value is a Go function returning one value (or a value and an error).

Common misunderstanding: "I can add a function after parsing." You cannot: the parser rejects a call to an unknown function. Register with Funcs before the first Parse/ParseFS. Another: "eq is ==." It is a function, it compares basic types loosely (any integer with any integer, but not int with float32), and with more than two arguments it means "equal to any of the rest": eq .Status "new" "paid".

Definition: template.FuncMap is map[string]any. Built-ins named in the doc: and, or, not, call, html (unavailable in html/template, "with a few exceptions"), index, slice, js, len, print, printf, println, urlquery (also restricted), and the comparison functions eq, ne, lt, le, gt, ge. "Unlike with || in Go, however, eq is a function call and all the arguments will be evaluated."

1  funcs := template.FuncMap{"money": Money, "plural": Plural, "dict": Dict}
2  template.New("").Funcs(funcs).ParseFS(...)           // Funcs BEFORE Parse
3  {{if eq .Status "new" "paid"}}                        // true for either
4  {{if and (gt .ID 5) (lt .ID 10)}}                     // parentheses group a call
5  {{printf "%05d|%-6s|" .ID .Status}}                   // 00007|paid  |
6  {{index .Lines 1}}   {{index .Tags "gift"}}           // slice element, map entry; a missing map key gives ""
7  {{.Total | money | printf "EUR %s"}}                  // 123.45 -> EUR 123.45

Real scenario: money formatting from integer cents; a date helper that prints "never" for the zero time; a plural helper for "1 item / 3 items"; an asset helper that maps app.css to a fingerprinted URL; a dict helper for nested templates; a safeIcon that returns template.HTML from constants.

FunctionSignatureReturnsNote
eq, ne(a, b any, rest ...any) for eqboolMulti-argument eq only
lt, le, gt, ge(a, b any)boolSame-kind basic types
printf(format string, args ...any)stringAlias of fmt.Sprintf
index(x any, keys ...any)elementSlices, arrays, maps; out of range is an error
len(x any)int
slice(x any, i, j, k ...int)subsliceStrings, slices, arrays
call(fn any, args ...any)resultFor func-valued fields
and, or, notvariadic / onean argument / booland/or stop early
html, urlquery, jsstringhtml and urlquery are unavailable in html/template, "with a few exceptions"

Fix / how to use it: keep helpers pure and small, return an error as second value for failure (execution stops with it), and test them in a table.

go
// Package funcs holds the template.FuncMap used by the render package and
// the helpers that make nested templates with several values possible.
package funcs

import (
	"errors"
	"fmt"
	"html/template"
	"time"
)

// Map returns the functions every page may call. Register them BEFORE parsing:
// a template that names an unknown function fails to parse.
func Map() template.FuncMap {
	return template.FuncMap{
		"dict":   Dict,
		"date":   Date,
		"plural": Plural,
		"money":  Money,
		"seq":    Seq,
	}
}

// Dict packs key/value pairs into a map so that {{template "field" dict ...}}
// can pass several values through the single dot a template call accepts.
func Dict(kv ...any) (map[string]any, error) {
	if len(kv)%2 != 0 {
		return nil, errors.New("dict: odd number of arguments")
	}
	m := make(map[string]any, len(kv)/2)
	for i := 0; i < len(kv); i += 2 {
		k, ok := kv[i].(string)
		if !ok {
			return nil, fmt.Errorf("dict: key %d is %T, want string", i/2, kv[i])
		}
		m[k] = kv[i+1]
	}
	return m, nil
}

// Date formats t as 2006-01-02 in UTC; the zero time renders as "never".
func Date(t time.Time) string {
	if t.IsZero() {
		return "never"
	}
	return t.UTC().Format("2006-01-02")
}

// Plural picks the singular or plural form for n. English has two forms; real
// i18n needs CLDR plural rules (see golang.org/x/text/message).
func Plural(n int, one, other string) string {
	if n == 1 {
		return one
	}
	return other
}

// Money formats cents as a decimal amount with two digits.
func Money(cents int64) string {
	sign := ""
	if cents < 0 {
		sign, cents = "-", -cents
	}
	return fmt.Sprintf("%s%d.%02d", sign, cents/100, cents%100)
}

// Seq returns 1..n for templates written for Go before 1.24 (range over int).
func Seq(n int) []int {
	out := make([]int, n)
	for i := range out {
		out[i] = i + 1
	}
	return out
}

Whitespace control Important ​

In plain words: A minus sign inside the braces, next to the action, eats the whitespace on that side. Use it to keep the generated HTML tidy and to stop blank lines from if/range lines.

Common misunderstanding: "{{-3}} trims whitespace before the number 3." The minus must be followed by a space to be a trim marker: {{- 3}} trims; {{-3}} is the number minus three. The text/template doc spells this out.

Definition: "If an action's left delimiter is followed immediately by a minus sign and white space, all trailing white space is trimmed from the immediately preceding text. Similarly, if the right delimiter is preceded by white space and a minus sign, all leading white space is trimmed from the immediately following text." White space means space, horizontal tab, carriage return and newline. The doc example: {{23 -}} < {{- 45}} prints 23<45.

1  a\n{{if true}}\nb\n{{end}}\nc          ->  a, blank, b, blank, c      (4 newlines from the template text survive)
2  a\n{{- if true}}\nb\n{{- end}}\nc      ->  a, b, c                    (the newline before each action is gone)
3  x {{-3}} y                             ->  x -3 y                      (the number, not a trim)
4  x {{- 3}} y                            ->  x3 y                        (trim before)

Real scenario: a <ul> generated with range that shows an empty line per item in the page source; a <pre> block where whitespace matters and trimming would damage it; inline elements where a stray space becomes visible; a plain-text e-mail template.

MarkerTrimsExample
left delimiter then minus then spaceText before the actiona {{- x}}
space then minus then right delimiterText after the action{{x -}} b
BothBoth sides{{- x -}}
NeitherNothingWhitespace preserved exactly

Fix / how to use it: do not trim reflexively; trim where blank lines or visible spaces appear. HTML collapses most whitespace anyway, so the main wins are readable output and tests that compare strings. The funcs test TestWhitespaceControl asserts all four lines above. The phrase to search for is whitespace control {{- -}}.

Nested templates with data: dict Important ​

In plain words: template accepts one value. To give a form-field partial a name, a label, a value and an error message, pack them into a map with a helper called dict and pass that.

Common misunderstanding: "I can pass several arguments like a function call." The syntax is template "name" pipeline: exactly one pipeline. dict is not built in; it is a ten-line function you register (the funcs package has it). Another: the called template does not see the caller's variables: $x declared outside is not visible inside; only dot crosses.

Definition: dict "Name" "email" "Label" "Email" returns map[string]any{"Name": "email", "Label": "Email"}; the partial reads .Name and .Label. The error cases (odd number of arguments, non-string key) are checked by the helper and abort execution with a clear message.

1  {{define "field"}}<label for="{{.Name}}">{{.Label}}</label><input name="{{.Name}}" value="{{.Value}}">{{with .Error}}<em>{{.}}</em>{{end}}{{end}}
2  {{template "field" dict "Name" "email" "Label" "Email" "Value" .Email "Error" .EmailErr}}
3  -> <label for="email">Email</label><input name="email" value="a&#34;b@x.test"><em>invalid</em>
4  {{template "inner"}}            -> inner sees a nil dot: prints nothing
5  {{template "inner" .}}          -> inner sees the caller's dot

Real scenario: every input in a form; a card component used by three pages; a table-row partial with an action URL; a breadcrumb with current page and parents; a pagination component taking Page and Total.

TechniqueProsCons
dict helperNamed arguments, no new typesKeys are strings: typos fail at run time
A struct per componentTyped, discoverableA type for each partial
Pass dot and reach into itZero ceremonyCouples the partial to the page type
Use templ or gomponentsReal function signaturesDifferent toolchain (alternatives)

Fix / how to use it: the field.gohtml partial and the contact.gohtml page in the render package; the whole form is four lines, and every field gets the same markup, error class and escaping.

html
{{define "field" -}}
<p class="field{{if .Error}} has-error{{end}}">
  <label for="{{.Name}}">{{.Label}}</label>
  <input id="{{.Name}}" name="{{.Name}}" type="{{.Type}}" value="{{.Value}}">
  {{- with .Error}}
  <span class="error">{{.}}</span>
  {{- end}}
</p>
{{- end}}

Render to a buffer, then write Must-know ​

In plain words: Run the template into memory first. Only if it succeeded do you send the status line and the page. If it failed, nothing has been sent, so you can still answer with a proper 500.

Common misunderstanding: "http.Error after a failed Execute fixes the response." Once a handler has written a byte, the status line is on the wire; WriteHeader afterwards only logs "superfluous response.WriteHeader call". The before test shows the result: status 200, a half page, and an error message glued to the end. The standard library warns about it in the doc of Execute: "If an error occurs executing the template or writing its output, execution stops, but partial results may already have been written to the output writer."

Definition: Render into a bytes.Buffer; on error return it (log it, answer 500, or render an error page into another buffer); on success set Content-Type, call WriteHeader(status), then buf.WriteTo(w). Buffers are pooled with sync.Pool; a buffer that grew beyond a threshold (64 KiB in the snippet) is dropped instead of returned, so one huge page does not pin memory.

1  handler           buf := pool.Get(); buf.Reset()
2  ExecuteTemplate   writes "<html>... row 1 ... row 2" into buf
3  row 3             {{.Price.Amount}} on a nil pointer -> error "nil pointer evaluating"
4  render returns    error; w untouched: no header, no body, no Content-Type
5  handler           http.Error(w, "Internal Server Error", 500)
6  -- without the buffer: step 2 wrote into w, so steps 3-5 end as status 200 plus a truncated page --

Real scenario: a product page with 40 rows where row 31 has a nil supplier; a template that calls a method which returns an error for one record; a client that disconnects mid-write (the error then comes from buf.WriteTo, which is a write error, not a template error: log at INFO and stop); a streaming page where buffering is wrong (see the table).

StrategyError before headersMemoryTime to first byteUse for
Buffer, then writeYes: clean 500Page sizeAfter the full renderNormal pages
Execute(w, ...) directNo: 200 plus broken pageConstantImmediateHuge or streaming output where partial is acceptable
Buffer + Content-LengthYesPage sizeAfter renderWhen a proxy likes it (Go sets it for small bodies anyway)
http.Flusher per sectionPartial by designConstantPer sectionProgressive rendering (accept that errors cannot change the status)
Execute into a buffer first, touch the ResponseWriter secondhandlera.show(w, r, ...)t.ExecuteTemplate(buf,"base", page)bytes.Bufferfrom a sync.Poolerror?nil pointer, missing key, func erroryes: log it, http.Error(w, ..., 500)status line not sent yet: the 500 is realno: Content-Type, WriteHeader(status),buf.WriteTo(w): one complete pageyesnobefore/ handler: Execute(w, ...)200 and half a page already sentCost: the whole page sits in memory for a moment. Reuse buffers with sync.Pool and drop outliers instead of pooling them.

Fix / how to use it: the Renderer.execute method above (all of it is in render.go); the render test TestExecutionErrorLeavesResponseUntouched asserts that the body is empty and no Content-Type was set after a failure, and that http.Error can still produce a 500 on the same recorder.

Forms: ParseForm, validation, re-rendering Must-know ​

In plain words: The browser sends the form as a body of key=value pairs. You read it with r.ParseForm(), check each field, and if something is wrong you show the same form again with a message next to each bad field and the values the user typed.

Common misunderstanding: "r.Form is the POST body." r.Form merges the URL query and the body (the documentation: "Request body parameters take precedence over URL query string values in r.Form"); r.PostForm is the body only. So a ?admin=1 appended to the action URL still shows up in r.Form, and r.FormValue("admin") returns it although the form never sent it; reading r.PostForm is the way to say "only what the form sent". The second one: "ParseForm limits the size." Not by your standards: the documentation of ParseForm says "If the request Body's size has not already been limited by MaxBytesReader, the size is capped at 10MB", which is far more than a contact form needs. Wrap r.Body with http.MaxBytesReader first.

Definition: ParseForm parses the query into r.Form and, for POST, PUT and PATCH with application/x-www-form-urlencoded, the body into r.PostForm (and r.Form). Multipart forms use ParseMultipartForm (see File uploads). It returns an error for a malformed or oversized body. Validation is application code: required, length (in runes, not bytes), format (net/mail.ParseAddress for e-mail), range, and cross-field rules.

1  GET  /contact          render empty form (CSRF token in a hidden input)
2  POST /contact          body: csrf_token=...&email=ann%40&message=
3  Decode                 MaxBytesReader(1 MiB) -> ParseForm -> r.PostForm
4  Validate               email: "Enter a valid email address"; message: "This field is required"
5  Re-render              status 422, same URL, the same template with Form{values, errors}
6  Template               value="{{.Value}}" prints the typed text, escaped; error span next to the field

Real scenario: a sign-up form where the e-mail is wrong; a checkout address with a postcode rule per country; a settings form that must keep the user's long text after an error; a form whose server-side limit (500 runes) differs from the HTML maxlength (never rely on the attribute).

ChoiceOption AOption BPrefer
Status on invalid input200 with the form422 Unprocessable Content (or 400)422: caches, proxies and htmx can tell failure from success
Where values liver.PostFormA decoded structA struct for large forms (go-playground/form)
Message per fieldmap[string]stringA slice of errorsMap: templates ask by field
Client-side validationOnlyPlus server-sideAlways server-side; client side is a courtesy
LibraryHand-written helpersgo-playground/validator struct tagsHelpers for a few forms, tags for many

Fix / how to use it: the forms package; Form keeps url.Values and an error map; helpers Required, MaxRunes, Email record the first error per field; Valid() decides; Decode caps the body and reads PostForm. The test proves query values are ignored, the validators agree on runes, and a 2 MiB body yields http: request body too large.

go
// Package forms parses an HTML form, validates it and keeps the submitted
// values so the page can be shown again with errors and sticky fields.
package forms

import (
	"net/http"
	"net/mail"
	"net/url"
	"strings"
	"unicode/utf8"
)

// Form is the submitted data plus one error message per field.
type Form struct {
	values url.Values
	errors map[string]string
}

// New wraps already parsed values.
func New(v url.Values) Form {
	if v == nil {
		v = url.Values{}
	}
	return Form{values: v, errors: map[string]string{}}
}

// Decode reads a POST body of at most 1 MiB. r.ParseForm returns an error for
// a malformed body and for one that exceeds the limit set by MaxBytesReader.
func Decode(w http.ResponseWriter, r *http.Request) (Form, error) {
	r.Body = http.MaxBytesReader(w, r.Body, 1<<20)
	if err := r.ParseForm(); err != nil {
		return Form{}, err
	}
	return New(r.PostForm), nil // PostForm: body only, not the URL query
}

// Value returns the submitted text of a field (used by templates).
func (f Form) Value(name string) string { return f.values.Get(name) }

// Error returns the message for a field, or "" (used by templates).
func (f Form) Error(name string) string { return f.errors[name] }

// Valid reports whether no field has an error.
func (f Form) Valid() bool { return len(f.errors) == 0 }

// Errors returns a copy of the messages.
func (f Form) Errors() map[string]string {
	out := make(map[string]string, len(f.errors))
	for k, v := range f.errors {
		out[k] = v
	}
	return out
}

func (f *Form) fail(name, msg string) {
	if _, taken := f.errors[name]; !taken { // first error per field wins
		f.errors[name] = msg
	}
}

// Required fails when the trimmed value is empty.
func (f *Form) Required(name string) {
	if strings.TrimSpace(f.values.Get(name)) == "" {
		f.fail(name, "This field is required")
	}
}

// MaxRunes fails when the value has more than n characters (not bytes).
func (f *Form) MaxRunes(name string, n int) {
	if utf8.RuneCountInString(f.values.Get(name)) > n {
		f.fail(name, "Too long")
	}
}

// Email fails when the value is not a bare address such as ann@example.test.
func (f *Form) Email(name string) {
	v := strings.TrimSpace(f.values.Get(name))
	if v == "" {
		return // Required reports the empty case
	}
	a, err := mail.ParseAddress(v)
	if err != nil || a.Address != v {
		f.fail(name, "Enter a valid email address")
	}
}
go
package forms

import (
	"net/http"
	"net/http/httptest"
	"net/url"
	"strings"
	"testing"
)

func post(body string) (*httptest.ResponseRecorder, *http.Request) {
	r := httptest.NewRequest(http.MethodPost, "/contact?email=query@x.test", strings.NewReader(body))
	r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	return httptest.NewRecorder(), r
}

func TestDecodeUsesBodyNotQuery(t *testing.T) {
	w, r := post("message=hi")
	f, err := Decode(w, r)
	if err != nil {
		t.Fatal(err)
	}
	if f.Value("message") != "hi" || f.Value("email") != "" {
		t.Fatalf("email from the query string must be ignored: %q", f.Value("email"))
	}
}

func TestValidation(t *testing.T) {
	cases := []struct {
		name string
		v    url.Values
		want map[string]string
	}{
		{"ok", url.Values{"email": {"ann@example.test"}, "message": {"hello"}}, map[string]string{}},
		{"empty", url.Values{}, map[string]string{"email": "This field is required", "message": "This field is required"}},
		{"bad email", url.Values{"email": {"ann@"}, "message": {"x"}}, map[string]string{"email": "Enter a valid email address"}},
		{"display name rejected", url.Values{"email": {"Ann <ann@example.test>"}, "message": {"x"}}, map[string]string{"email": "Enter a valid email address"}},
		{"too long counts runes", url.Values{"email": {"a@b.test"}, "message": {strings.Repeat("é", 6)}}, map[string]string{"message": "Too long"}},
	}
	for _, c := range cases {
		f := New(c.v)
		f.Required("email")
		f.Email("email")
		f.Required("message")
		f.MaxRunes("message", 5)
		got := f.Errors()
		if len(got) != len(c.want) {
			t.Errorf("%s: got %v want %v", c.name, got, c.want)
			continue
		}
		for k, v := range c.want {
			if got[k] != v {
				t.Errorf("%s: %s = %q want %q", c.name, k, got[k], v)
			}
		}
		if f.Valid() != (len(c.want) == 0) {
			t.Errorf("%s: Valid() wrong", c.name)
		}
	}
}

func TestBodyLimit(t *testing.T) {
	w, r := post("message=" + strings.Repeat("a", 2<<20))
	if _, err := Decode(w, r); err == nil {
		t.Fatal("expected an error for a body over 1 MiB")
	} else {
		t.Log(err)
	}
}

Post/Redirect/Get Must-know ​

In plain words: After a successful POST, do not render a page; redirect the browser to a GET. Then refreshing the page repeats the GET, not the POST, so a refresh cannot place the order twice.

Common misunderstanding: "302 is the redirect after a POST." Historically browsers turned a 302 after a POST into a GET, but the standard does not require it; 307 and 308 explicitly keep the method. The status made for this job is 303 See Other: the client must follow with GET. In Go, http.Redirect(w, r, "/", http.StatusSeeOther) (the constant is StatusSeeOther).

Definition: PRG is a three-step pattern: the POST validates and acts; a success answers 303 with a Location; the browser issues a GET for that location. A failure does not redirect: it answers 422 with the form, because the typed values live in the request that just failed and a redirect would lose them (or force you to stash them in the session).

1  POST /contact  (valid)         -> action done, flash cookie queued
2  303 See Other  Location: /     -> body empty or a link
3  GET  /         (browser follows, method forced to GET)
4  200            page with the flash message
5  F5 in the browser              -> repeats step 3, not step 1
6  POST /contact  (invalid)       -> 422 + form with errors (no redirect, values kept)

Real scenario: an order form where a double POST charges twice; a comment form where F5 duplicated the comment; a settings page where "Back" after saving asked to resubmit; an API-ish form where a successful create redirects to the new resource's page.

StatusMethod of the follow-up requestUse
301, 302Browsers usually switch POST to GET; not guaranteedMoved resources (legacy)
303 See OtherAlways GETPRG after POST
307 Temporary RedirectSame method and bodyKeep a POST (rare for forms)
308 Permanent RedirectSame method and bodyPermanent move that keeps the method
Form round trip: token in, 422 or 303 out, flash shown onceBrowserServer (net/http)1 GET /contactcsrf cookie + hidden csrf_token, CSP nonce2 POST /contact (bad email)CSRF ok, validation fails 422 + same form, errors, typed values kept3 POST /contact (valid)csrf token checked first (403 if wrong) 303 See Other, Location: /, Set-Cookie: flash=signed4 GET / (browser follows with GET, F5 cannot re-POST)Cookie: flash 200 page with the flash div, Set-Cookie: flash; Max-Age=-1

Fix / how to use it: contactSubmit in app.go: validate, on failure 422 plus form, on success store, queue a flash, http.Redirect(..., http.StatusSeeOther). PRG does not make the write idempotent: a double-click can still send two POSTs; add an idempotency key or a unique constraint for that (see Idempotency keys).

CSRF token in forms Must-know ​

In plain words: A form that changes something must prove it was served by your site. You put a secret value in the form and in a cookie; an attacker's page can make the browser send the cookie but cannot read the secret, so their POST fails.

Common misunderstanding: "SameSite=Lax cookies make CSRF tokens unnecessary." They remove the classic cross-site POST in modern browsers, but not same-site attacks from a sibling subdomain, not old browsers, and not GET requests that change state. Token or origin checking is still the standard answer, and the other way round: "a CSRF token protects me from XSS". It does not: the OWASP cheat sheet warns that "Cross-Site Scripting (XSS) can defeat all CSRF mitigation techniques".

Definition: Two mechanisms in the standard toolbox. (1) A token: the csrf package issues a random id in an HttpOnly, SameSite=Lax cookie and a form token HMAC-SHA256(key, id) in a hidden csrf_token input (or the X-CSRF-Token header for fetch); unsafe methods must present a matching token or get 403; comparison uses hmac.Equal. OWASP's cheat sheet recommends the synchronizer token pattern for stateful software and double-submit cookies for stateless software; this package is the signed double-submit variant. OWASP also warns that "simply signing tokens without session binding provides minimal protection and remains vulnerable to cookie injection attacks", which is why Protect takes an optional bind function: pass the session id of a logged-in user and the token is tied to it. (2) Origin checking: since Go 1.25 http.CrossOriginProtection rejects non-safe cross-origin browser requests using Sec-Fetch-Site or by comparing Origin and Host; GET, HEAD and OPTIONS are always allowed, and requests without those headers are assumed same-origin or non-browser. It needs no token and no template change.

1  GET  /contact       server: no cookie -> set csrf_id=<32 random bytes, base64url>; token = HMAC(key, id, bound session id or "")
2  render              <input type="hidden" name="csrf_token" value="{{.CSRF}}">
3  POST /contact       cookie csrf_id (sent by the browser) + form field csrf_token
4  server              recompute HMAC(key, cookie) ; hmac.Equal(field, recomputed) ? continue : 403
5  evil.example POST   cross-site form: the browser may attach the cookie, but the page cannot read the token -> 403
6  other browser       a token issued for cookie A with cookie B -> 403 (bound to its cookie)

Real scenario: a "delete account" form; a transfer-money form; a settings change; a logout that is a POST; an htmx request that must send the token as a header (hx-headers); an admin panel behind a session cookie.

DefenceNeeds a token in templatesBrowser supportCostNote
Hidden token (this package, gorilla/csrf with csrf.TemplateField)YesAllOne field per formWorks everywhere
http.CrossOriginProtection (Go 1.25)NoSec-Fetch-Site in all browsers since 2023 (per the Go doc)Middleware onlyCombine with a token for defence in depth
SameSite=Lax session cookieNoModern browsersNoneDefence in depth, not a replacement
Custom header on fetchNo (JS adds it)AllJSFor XHR/fetch, not for plain forms
Re-authentication for sensitive actionsNoAllUXAdditional layer

Fix / how to use it: wrap the page router with csrf.Protect and put {{.CSRF}} in a hidden input (the contact page does). The csrf tests prove a valid token passes both as form field and as header; a missing, tampered or foreign token is 403; a token issued for one browser's cookie fails with another's. Keep the HMAC key in configuration and rotate it. A test proves that a token issued for one session id is rejected under another even with the same cookie. The demo site has no login, so it passes nil for bind; a real application passes its session id. Note that this simple token is not masked against BREACH-style compression oracles; if you serve secrets in compressed responses use a masked token library.

go
// Package csrf implements a signed double-submit token for HTML forms: the
// browser holds a random id in a cookie, the form carries HMAC(key, id), and
// every unsafe request must present a token that matches its cookie.
//
// A random cookie id alone is the weak form of the pattern: OWASP calls signing
// without session binding "minimal protection" that "remains vulnerable to
// cookie injection attacks". When users log in, pass bind so that the token is
// also tied to the authenticated session (for example the session id).
//
// Since Go 1.25 net/http also has CrossOriginProtection, which checks the
// Sec-Fetch-Site and Origin headers and needs no token; use it alongside or
// instead when all your users have modern browsers.
package csrf

import (
	"context"
	"crypto/hmac"
	"crypto/rand"
	"crypto/sha256"
	"encoding/base64"
	"net/http"
)

const (
	cookieName = "csrf_id"
	// FieldName is the hidden input the form must carry.
	FieldName = "csrf_token"
	// HeaderName is accepted for fetch/XHR requests.
	HeaderName = "X-CSRF-Token"
)

type ctxKey struct{}

// Protect wraps next. Safe methods pass through (and receive a token via the
// context); every other method needs a valid token or gets 403. bind may be
// nil; when set, its result (for example a session id) is mixed into the token.
func Protect(key []byte, secure bool, bind func(*http.Request) string, next http.Handler) http.Handler {
	token := func(id, session string) string {
		mac := hmac.New(sha256.New, key)
		mac.Write([]byte(id))
		mac.Write([]byte{0}) // separator: "ab"+"c" must differ from "a"+"bc"
		mac.Write([]byte(session))
		return base64.RawURLEncoding.EncodeToString(mac.Sum(nil))
	}
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		id := ""
		if c, err := r.Cookie(cookieName); err == nil && len(c.Value) == 43 {
			id = c.Value
		} else {
			b := make([]byte, 32)
			if _, err := rand.Read(b); err != nil {
				http.Error(w, "Internal Server Error", http.StatusInternalServerError)
				return
			}
			id = base64.RawURLEncoding.EncodeToString(b)
			http.SetCookie(w, &http.Cookie{Name: cookieName, Value: id, Path: "/", HttpOnly: true, Secure: secure, SameSite: http.SameSiteLaxMode})
		}
		session := ""
		if bind != nil {
			session = bind(r)
		}
		want := token(id, session)
		switch r.Method {
		case http.MethodGet, http.MethodHead, http.MethodOptions, http.MethodTrace:
		default:
			got := r.Header.Get(HeaderName)
			if got == "" {
				// PostFormValue parses the whole body, so cap it first.
				r.Body = http.MaxBytesReader(w, r.Body, 1<<20)
				// PostFormValue ignores parse errors, so parse explicitly: a body that
				// does not parse must not reach the handler with half its fields.
				if err := r.ParseForm(); err != nil {
					http.Error(w, "Bad Request", http.StatusBadRequest)
					return
				}
				got = r.PostForm.Get(FieldName)
			}
			if !hmac.Equal([]byte(got), []byte(want)) {
				http.Error(w, "Forbidden", http.StatusForbidden)
				return
			}
		}
		next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), ctxKey{}, want)))
	})
}

// Token returns the form token for this request ("" outside Protect).
func Token(ctx context.Context) string {
	s, _ := ctx.Value(ctxKey{}).(string)
	return s
}
go
package csrf

import (
	"net/http"
	"net/http/httptest"
	"net/url"
	"strings"
	"testing"
)

var key = []byte("0123456789abcdef0123456789abcdef")

func handler() http.Handler {
	return Protect(key, false, nil, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.Method == http.MethodGet {
			_, _ = w.Write([]byte(Token(r.Context())))
			return
		}
		_, _ = w.Write([]byte("done"))
	}))
}

func get(t *testing.T) (token string, cookie *http.Cookie) {
	t.Helper()
	rec := httptest.NewRecorder()
	handler().ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/form", nil))
	cs := rec.Result().Cookies()
	if len(cs) != 1 || !cs[0].HttpOnly || cs[0].SameSite != http.SameSiteLaxMode {
		t.Fatalf("cookie: %+v", cs)
	}
	return rec.Body.String(), cs[0]
}

func post(token string, c *http.Cookie, header bool) *httptest.ResponseRecorder {
	body := url.Values{FieldName: {token}}.Encode()
	r := httptest.NewRequest(http.MethodPost, "/form", strings.NewReader(body))
	r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	if header {
		r.Header.Set(HeaderName, token)
	}
	if c != nil {
		r.AddCookie(c)
	}
	rec := httptest.NewRecorder()
	handler().ServeHTTP(rec, r)
	return rec
}

func TestValidTokenPasses(t *testing.T) {
	tok, c := get(t)
	if rec := post(tok, c, false); rec.Code != 200 || rec.Body.String() != "done" {
		t.Fatalf("form field: %d %s", rec.Code, rec.Body)
	}
	if rec := post(tok, c, true); rec.Code != 200 {
		t.Fatalf("header: %d", rec.Code)
	}
}

func TestMissingOrWrongTokenIs403(t *testing.T) {
	tok, c := get(t)
	for name, rec := range map[string]*httptest.ResponseRecorder{
		"no token":    post("", c, false),
		"wrong token": post("AAAA"+tok[4:], c, false),
		"no cookie":   post(tok, nil, false), // a cross-site POST carries no cookie of ours
	} {
		if rec.Code != http.StatusForbidden {
			t.Errorf("%s: status %d, want 403", name, rec.Code)
		}
	}
}

func TestTokenFromAnotherBrowserFails(t *testing.T) {
	tokA, _ := get(t)
	_, cookieB := get(t)
	if rec := post(tokA, cookieB, false); rec.Code != http.StatusForbidden {
		t.Fatalf("status %d: a token is bound to the cookie that was issued with it", rec.Code)
	}
}

func TestTokenIsBoundToTheSession(t *testing.T) {
	var session string
	h := Protect(key, false, func(*http.Request) string { return session }, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.Method == http.MethodGet {
			_, _ = w.Write([]byte(Token(r.Context())))
			return
		}
		_, _ = w.Write([]byte("done"))
	}))
	session = "session-A"
	rec := httptest.NewRecorder()
	h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/", nil))
	tok, cookie := rec.Body.String(), rec.Result().Cookies()[0]

	send := func() int {
		r := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(url.Values{FieldName: {tok}}.Encode()))
		r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
		r.AddCookie(cookie)
		w := httptest.NewRecorder()
		h.ServeHTTP(w, r)
		return w.Code
	}
	if code := send(); code != 200 {
		t.Fatalf("same session: %d", code)
	}
	session = "session-B" // an attacker-injected cookie id cannot be reused across sessions
	if code := send(); code != http.StatusForbidden {
		t.Fatalf("other session: %d, want 403", code)
	}
}

func TestMalformedBodyIs400EvenWithValidToken(t *testing.T) {
	tok, c := get(t)
	body := url.Values{FieldName: {tok}}.Encode() + "&bad=%ZZ"
	r := httptest.NewRequest(http.MethodPost, "/form", strings.NewReader(body))
	r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	r.AddCookie(c)
	rec := httptest.NewRecorder()
	handler().ServeHTTP(rec, r)
	if rec.Code != http.StatusBadRequest {
		t.Fatalf("status %d, want 400: a body that fails to parse must not reach the handler", rec.Code)
	}
}

Flash messages via a session cookie Must-know ​

In plain words: A flash message is a note you leave for the next page: "Saved." You write it before the redirect; the next request reads it and deletes it, so it shows once.

Common misunderstanding: "Flash needs a session store." It needs somewhere that survives one redirect. A short, signed cookie is enough for a sentence; a server-side session is better when you already have one or when the message is long or sensitive. And the other trap: a cookie value is user-controlled text, so it must be signed (tamper-proof) and still escaped at output; signing is not the same as safe HTML.

Definition: The flash package serialises {level, text} as JSON, base64url-encodes it, appends . and an HMAC-SHA256 signature, and sets it as an HttpOnly, SameSite=Lax, Max-Age=60 cookie. Pop verifies the signature with hmac.Equal, decodes the message and always expires the cookie so a second page shows nothing. Alex Edwards' post "Simple 'Flash' Messages in Go" builds the same idea ("your own cookie-based flash messages"). Libraries such as alexedwards/scs offer the same through server-side sessions: its README lists "flash messages" among its features, alongside session token regeneration and idle and absolute timeouts.

1  POST /contact (valid)    flash.Set(w, {success, "Thanks, we will answer soon."})   Set-Cookie: flash=<b64>.<sig>; Max-Age=60
2  303 Location: /
3  GET /                    Cookie: flash=...       Pop: verify, decode, Set-Cookie: flash=; Max-Age=-1
4  200                      <div class="flash flash-success" role="status">Thanks, ...</div>
5  GET /  (again)           no cookie               no flash div
6  forged cookie            wrong signature         ignored

Real scenario: "Profile saved", "Item deleted", "Password changed, please log in again" after a redirect to the login page; an error flash after a failed import; success messages after a PRG; a logout that flashes "You are signed out".

StorageSurvives one redirectSizeTamper protectionNeeds server stateUse for
Signed cookie (this package)YesAbout 4 KB, per cookieHMACNoShort messages
Server-side session (scs, Laravel session()->flash)YesAnythingServer holds itYesApps that already have sessions
Query string (/?saved=1)YesTinyNoneNoNever for text (it is user-controlled and reload-sticky)
Database row popped on readYesAnythingServer holds itYesMulti-server flash without a session library (see the SQL below)

Fix / how to use it: the flash package, called from contactSubmit (Set) and from the page builder (Pop), which hands the message to the layout as Page.Flash; the flash partial prints it with the normal escaping.

sql
-- Server-side flash for several app servers, popped atomically (PostgreSQL).
CREATE TABLE flash_messages (
  session_id text        NOT NULL,
  level      text        NOT NULL CHECK (level IN ('success', 'error', 'info')),
  body       text        NOT NULL,
  created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX ON flash_messages (session_id);

-- On the page after the redirect: read and delete in one statement.
DELETE FROM flash_messages
WHERE session_id = $1
  AND created_at > now() - interval '1 minute'
RETURNING level, body
go
// Package flash stores a one-shot message in a signed cookie: written before
// a redirect, read and deleted by the next request. For anything bigger than
// a sentence, or when you already have server-side sessions, put the message
// in the session instead (for example alexedwards/scs, which supports flash).
package flash

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/base64"
	"encoding/json"
	"net/http"
	"strings"
)

const cookieName = "flash"

// Message is what the next page shows.
type Message struct {
	Level string `json:"l"`
	Text  string `json:"t"`
}

// Manager signs and verifies the cookie value with HMAC-SHA256.
type Manager struct {
	key    []byte
	Secure bool // set true behind HTTPS
}

// New returns a manager; key should be 32 random bytes kept out of source code.
func New(key []byte) *Manager { return &Manager{key: key} }

func (m *Manager) sign(payload string) string {
	mac := hmac.New(sha256.New, m.key)
	mac.Write([]byte(payload))
	return base64.RawURLEncoding.EncodeToString(mac.Sum(nil))
}

// Set queues msg for the next request. Call it before w.WriteHeader or a redirect.
func (m *Manager) Set(w http.ResponseWriter, msg Message) {
	raw, _ := json.Marshal(msg)
	payload := base64.RawURLEncoding.EncodeToString(raw)
	http.SetCookie(w, &http.Cookie{
		Name:     cookieName,
		Value:    payload + "." + m.sign(payload),
		Path:     "/",
		MaxAge:   60, // stale flashes disappear on their own
		HttpOnly: true,
		Secure:   m.Secure,
		SameSite: http.SameSiteLaxMode,
	})
}

// Pop returns the queued message, if any and if the signature checks out, and
// always clears the cookie so the message is shown once.
func (m *Manager) Pop(w http.ResponseWriter, r *http.Request) (*Message, bool) {
	c, err := r.Cookie(cookieName)
	if err != nil {
		return nil, false
	}
	http.SetCookie(w, &http.Cookie{Name: cookieName, Value: "", Path: "/", MaxAge: -1, HttpOnly: true, Secure: m.Secure, SameSite: http.SameSiteLaxMode})
	payload, sig, ok := strings.Cut(c.Value, ".")
	if !ok || !hmac.Equal([]byte(sig), []byte(m.sign(payload))) {
		return nil, false
	}
	raw, err := base64.RawURLEncoding.DecodeString(payload)
	if err != nil {
		return nil, false
	}
	var msg Message
	if json.Unmarshal(raw, &msg) != nil {
		return nil, false
	}
	return &msg, true
}
go
package flash

import (
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
)

func roundTrip(m *Manager, set *httptest.ResponseRecorder) (*http.Request, *httptest.ResponseRecorder) {
	r := httptest.NewRequest(http.MethodGet, "/", nil)
	for _, c := range set.Result().Cookies() {
		r.AddCookie(c)
	}
	return r, httptest.NewRecorder()
}

func TestSetThenPopOnce(t *testing.T) {
	m := New([]byte("0123456789abcdef0123456789abcdef"))
	set := httptest.NewRecorder()
	m.Set(set, Message{Level: "success", Text: "Thanks <3"})
	c := set.Result().Cookies()[0]
	if !c.HttpOnly || c.SameSite != http.SameSiteLaxMode || c.MaxAge != 60 {
		t.Errorf("cookie attributes: %+v", c)
	}
	r, w := roundTrip(m, set)
	msg, ok := m.Pop(w, r)
	if !ok || msg.Text != "Thanks <3" || msg.Level != "success" {
		t.Fatalf("pop = %v %v", msg, ok)
	}
	cleared := w.Result().Cookies()[0]
	if cleared.MaxAge != -1 {
		t.Errorf("the cookie must be cleared, MaxAge = %d", cleared.MaxAge)
	}
	// A request without the cookie (the browser obeyed the delete) sees nothing.
	if _, ok := m.Pop(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/", nil)); ok {
		t.Error("second request must not see the message")
	}
}

func TestTamperedOrForeignCookieIsIgnored(t *testing.T) {
	m := New([]byte("0123456789abcdef0123456789abcdef"))
	other := New([]byte("another-key-another-key-another!"))
	set := httptest.NewRecorder()
	other.Set(set, Message{Level: "error", Text: "forged"})
	r, w := roundTrip(m, set)
	if _, ok := m.Pop(w, r); ok {
		t.Fatal("a cookie signed with another key must be rejected")
	}
	set = httptest.NewRecorder()
	m.Set(set, Message{Level: "info", Text: "hi"})
	c := set.Result().Cookies()[0]
	c.Value = strings.Replace(c.Value, c.Value[:4], "AAAA", 1) // flip the payload
	r = httptest.NewRequest(http.MethodGet, "/", nil)
	r.AddCookie(c)
	if _, ok := m.Pop(httptest.NewRecorder(), r); ok {
		t.Fatal("a modified payload must be rejected")
	}
}

i18n and pluralization: a pointer Good to know ​

In plain words: "1 item" and "2 items" is the easy case. Other languages have several plural forms, different word order and different number formats. Do not build that with if eq .N 1; use a library built on the Unicode CLDR rules.

Common misunderstanding: "A plural helper with two arguments is internationalisation." It is English-only. Russian, Arabic and Polish have more than two forms, and word order changes with the sentence. The Plural function in the funcs snippet says so in its comment.

Definition: The Go team's golang.org/x/text/message package provides a Printer "language-specific formatted I/O analogous to the fmt package" created with message.NewPrinter(language.French); it includes the plural feature for generated catalogs. The community library github.com/nicksnyder/go-i18n supports "pluralized strings for all 200+ languages in the Unicode Common Locale Data Repository (CLDR)" and "strings with named variables using text/template syntax", through a Bundle (loaded once) and a Localizer per request (from Accept-Language). Alex Edwards' tutorial "i18n: managing translations" walks through golang.org/x/text/language and message with variables and pluralised translations. Either plugs into a template as a FuncMap entry bound per request, which means the template set is built once and the function that knows the language is supplied through the data (for example {{ call .T "items_count" 3 }}: a function-valued field is not a method, so it must go through call, which the funcs test TestFunctionValuedFieldNeedsCall proves; the failure without it is T has arguments but cannot be invoked as function) or through a clone per language.

1  request            Accept-Language: de, en;q=0.8  ->  localizer for [de, en]
2  page data          Page{T: localizer.Translate}      (a func-valued field: a method value, not a global function)
3  template           {{call .T "cart.items" 3}}        ->  "3 Artikel"   (a function-valued field needs call; .T "x" would fail)
4  message catalog    cart.items: one: "{{.Count}} Artikel", other: "{{.Count}} Artikel"   (CLDR categories per language)
5  number / date      printer.Sprintf("%d", 1234567)    ->  "1.234.567" for de

Real scenario: a shop in English and German; right-to-left Arabic pages (dir attribute, mirrored layout); a plural like "1 file selected / 2 files selected / 5 files selected" in Polish with three forms; prices and dates formatted per locale.

NeedToolNote
Number, currency, date formatting per localex/text/message, x/text/numberPrinter per request
Translated sentences with pluralsgo-i18n, x/text catalogsCLDR categories: zero, one, two, few, many, other
Language negotiationx/text/language matcher on Accept-LanguageFall back to a default
Just English pluralA tiny helper (plural)Fine until the second language

Fix / how to use it: keep message ids in templates, translations in files embedded with embed, and a Localizer or Printer created per request and stored in Page. This chapter does not go further: it is a pointer, and the second language is the right moment to adopt a library.

Static assets and cache busting Important ​

In plain words: Browsers cache CSS and JavaScript aggressively. To ship a change you must change the URL. Put a hash of the file's content into its name; the URL changes exactly when the content does, so you can tell the browser to cache it for a year.

Common misunderstanding: "?v=1.2 in the URL is enough." Some proxies ignore the query string for caching, and a manual version number is forgotten. The other one: "Cache-Control: max-age=31536000 on app.css is fine." Without a changing name, users will run the old CSS for a year.

Definition: The assets package hashes every embedded file at start-up (first four bytes of SHA-256, eight hex characters), maps app.css to app.<hash>.css, exposes Path(name) to the templates as asset, and serves only the hashed names with Cache-Control: public, max-age=31536000, immutable. http.FileServerFS handles Content-Type, Last-Modified and Range for the underlying file. Laravel's counterpart is Vite: @vite([...]) reads a manifest that maps source files to hashed build outputs.

1  start-up            assets.New(embedFS): sha256(app.css)[:4] = fa9a310f  ->  app.fa9a310f.css
2  template            <link rel="stylesheet" href="{{asset "app.css"}}">  ->  /static/app.fa9a310f.css
3  browser             GET /static/app.fa9a310f.css   200, Cache-Control: public, max-age=31536000, immutable
4  next page view      served from the browser cache, no request
5  you edit app.css    rebuild -> new hash app.0b17c2de.css -> HTML references the new name
6  GET /static/app.css 404 (only fingerprinted names are served)

Real scenario: a CSS tweak that half the users never see; a JavaScript bundle that must match the HTML that loads it; a CDN in front that should cache static files for a year but HTML for seconds; a service worker that holds on to an old file.

TechniqueBusts on changeCache lifetimeCost
Hash in the file nameYes1 year, immutableA map built at start-up
?v=<hash> queryYes (not for some proxies)LongSimple, a little fragile
Manual version in the nameOnly if you rememberLongHuman error
ETag / Last-Modified revalidationYes, with a request each timeShortOne conditional request per use
No cachingYesNoneSlow pages

Fix / how to use it: the assets tests assert the shape /static/app.<8 hex>.css, immutable in the header, that content changes change the URL, and that only the fingerprinted names are served. In production put a CDN in front of /static/ (see File uploads, S3 & CDN).

go
// Package assets fingerprints static files: app.css is served as
// app.<hash>.css with a one-year immutable cache lifetime, and the hash
// changes whenever the content does, so browsers never keep a stale copy.
package assets

import (
	"crypto/sha256"
	"embed"
	"encoding/hex"
	"fmt"
	"io/fs"
	"net/http"
	"path"
	"strings"
)

//go:embed static
var embedded embed.FS

// FS returns the embedded static tree rooted at "static".
func FS() fs.FS {
	sub, err := fs.Sub(embedded, "static")
	if err != nil {
		panic(err) // embedded at build time
	}
	return sub
}

// Registry maps logical names to fingerprinted names and back.
type Registry struct {
	fsys    fs.FS
	prefix  string
	forward map[string]string // app.css -> app.3f2a9c1b.css
	reverse map[string]string // app.3f2a9c1b.css -> app.css
}

// New hashes every file once, at start-up.
func New(fsys fs.FS, urlPrefix string) (*Registry, error) {
	r := &Registry{fsys: fsys, prefix: strings.TrimRight(urlPrefix, "/"), forward: map[string]string{}, reverse: map[string]string{}}
	err := fs.WalkDir(fsys, ".", func(p string, d fs.DirEntry, err error) error {
		if err != nil || d.IsDir() {
			return err
		}
		b, err := fs.ReadFile(fsys, p)
		if err != nil {
			return err
		}
		sum := sha256.Sum256(b)
		ext := path.Ext(p)
		hashed := fmt.Sprintf("%s.%s%s", strings.TrimSuffix(p, ext), hex.EncodeToString(sum[:4]), ext)
		r.forward[p] = hashed
		r.reverse[hashed] = p
		return nil
	})
	if err != nil {
		return nil, err
	}
	return r, nil
}

// Path returns the public URL for a logical name; unknown names are returned
// unchanged under the prefix so a typo shows up as a 404 in the browser.
func (r *Registry) Path(name string) string {
	if h, ok := r.forward[name]; ok {
		return r.prefix + "/" + h
	}
	return r.prefix + "/" + name
}

// Handler serves fingerprinted names only.
func (r *Registry) Handler() http.Handler {
	files := http.FileServerFS(r.fsys)
	return http.StripPrefix(r.prefix+"/", http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		orig, ok := r.reverse[req.URL.Path]
		if !ok {
			http.NotFound(w, req)
			return
		}
		w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
		req2 := req.Clone(req.Context())
		req2.URL.Path = "/" + orig
		files.ServeHTTP(w, req2)
	}))
}

Partial rendering for htmx Important ​

In plain words: htmx lets a button ask the server for a piece of HTML and swap it into the page. The server's job is to return only that piece. With named templates you already have the piece: render the define that holds it.

Common misunderstanding: "An htmx request is a normal request, return the full page." Then the list appears nested inside itself. The opposite trap: "every HX-Request wants a fragment". Boosted links (hx-boost) also send HX-Request: true and also HX-Boosted: true, and they swap the whole body, so they need the full page.

Definition: The htmx reference lists the request headers: HX-Request is "always true", HX-Target is the id of the target element, HX-Boosted "indicates that the request is via an element using hx-boost". The server answers the same URL in two shapes, so the response varies on a request header and must say so: Vary: HX-Request, HX-Boosted, or a cache will serve a fragment to a full-page request. Alex Edwards' "How I use htmx with Go" covers "structuring HTML templates and sending back partial and full-page HTML responses" with the same templates. The item-list template lives in the page file; RenderBlock(w, 200, "items", "item-list", data) executes just that name.

1  GET /items                              full page: layout + nav + item-list + scripts       Vary: HX-Request, HX-Boosted
2  button hx-get="/items?page=2" hx-target="#item-list" hx-swap="outerHTML"
3  GET /items?page=2   HX-Request: true    -> RenderBlock "item-list": <ul id="item-list">...</ul>
4  browser (htmx)      swaps the <ul> in place, no reload
5  GET /items  HX-Request: true  HX-Boosted: true   -> full page (boost replaces the body)
6  CDN / proxy         keys the cache on HX-Request and HX-Boosted thanks to Vary

Real scenario: "load more" and infinite scroll; an inline edit that replaces one table row; a search-as-you-type that returns result rows; a form that returns the form again with errors (a 422 fragment); an out-of-band swap that updates the cart count.

RequestResponseTemplate callHeaders
Plain GETFull pageRender(w, 200, "items", page)Vary: HX-Request, HX-Boosted
HX-Request: trueFragmentRenderBlock(w, 200, "items", "item-list", data)Vary: HX-Request, HX-Boosted
HX-Request and HX-BoostedFull pageRenderVary: HX-Request, HX-Boosted
Form POST with errors (htmx)Fragment with 422RenderBlock(... "form" ...)By default htmx does not swap 4xx and 5xx responses; configure htmx.config.responseHandling or send 200
After successHX-Redirect or HX-Location response headernoneClient-side redirect without a full reload

Fix / how to use it: itemsPage in app.go; the render test TestRenderBlockForHTMXFragment asserts that a fragment contains no layout, and the app test TestHTMXFragmentVersusFullPage covers all three request shapes. The layout loads a vendored htmx.min.js (htmx 2.0.4, in assets/static, fingerprinted like the CSS, no CDN) and sets <meta name="htmx-config" content='{"includeIndicatorStyles":false}'> because htmx otherwise injects an inline style that the policy style-src 'self' blocks. Remember the CSRF token: htmx must send it (for example hx-headers='{"X-CSRF-Token": "..."}' on the body), which the csrf package accepts as a header.

html
{{define "title"}}Items{{end}}
{{define "content" -}}
<h1>Items</h1>
<button hx-get="/items?page={{.Data.Next}}" hx-target="#item-list" hx-swap="outerHTML">More</button>
{{template "item-list" .Data}}
{{- end}}
{{define "item-list" -}}
<ul id="item-list">
{{- range .Items}}
  <li>{{.Name}}: {{.Qty}} {{plural .Qty "unit" "units"}} at {{money .Cents}}</li>
{{- else}}
  <li>No items.</li>
{{- end}}
</ul>
{{- end}}

Content-Security-Policy with nonces Important ​

In plain words: A Content-Security-Policy header tells the browser which scripts it may run. With a per-response random "nonce", only script tags that carry that exact value run, so an injected <script> with no nonce is ignored even if the escaper missed something.

Common misunderstanding: "A fixed nonce in the config is fine." The whole point is unpredictability: MDN says the nonce "must be different for every HTTP response, and must not be predictable", which also means "the server cannot serve static HTML, because it must insert a new nonce each time. Typically the server would use a templating engine to insert the nonce." Also: a nonce is not for avoiding the work of moving inline scripts out; MDN's advice is to use one only "for cases where you have no way around using unsafe inline script".

Definition: The csp middleware generates 16 random bytes per response, base64-encodes them, writes Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-<value>'; style-src 'self'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'self' and stores the nonce in the request context. The layout puts it on every inline script: <script nonce="{{.Nonce}}">. html/template treats the attribute as plain text, so the value is HTML-attribute-escaped like any other.

1  request           csp.Middleware: nonce = base64(16 random bytes) = "kQ3...=="
2  response header   Content-Security-Policy: script-src 'self' 'nonce-kQ3...=='; object-src 'none'; ...
3  response body     <script nonce="kQ3...==">document.documentElement.classList.add("js");</script>
4  attacker injects  <script>stealCookies()</script>   (no nonce)
5  browser           blocks it and reports a CSP violation in the console (and to a report endpoint, if you set one)
6  next request      a new nonce; the old one is useless

Real scenario: a page with one small inline bootstrap script; an analytics tag the marketing team inserts; a third-party widget that injects a script (needs 'strict-dynamic', see MDN); a Laravel app that sets Vite::useCspNonce(); a report-only rollout (the Content-Security-Policy-Report-Only header) before enforcing.

ApproachStrengthCost
No inline scripts, script-src 'self'Strongest, simplestMove code to files
Nonce per responseAllows chosen inline scriptsDynamic HTML on every response; no full-page caching
Hash ('sha256-...') of a static inline scriptNo per-request work, cacheableBreaks when the script changes
'unsafe-inline'None for scriptsDefeats the purpose

Fix / how to use it: the csp middleware, the Nonce field in render.Page, and an app test asserting that the nonce in the header equals the one on every inline script. Inline event handlers (onclick=) are blocked by this policy; use addEventListener in a static file.

go
// Package csp adds a Content-Security-Policy with a fresh nonce per response.
// Inline <script nonce="..."> blocks run; injected inline scripts do not.
package csp

import (
	"context"
	"crypto/rand"
	"encoding/base64"
	"net/http"
)

type ctxKey struct{}

// Middleware generates 16 random bytes per response, puts the nonce in the
// policy header and in the request context for the template data.
func Middleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		b := make([]byte, 16)
		if _, err := rand.Read(b); err != nil {
			http.Error(w, "Internal Server Error", http.StatusInternalServerError)
			return
		}
		nonce := base64.StdEncoding.EncodeToString(b)
		w.Header().Set("Content-Security-Policy",
			"default-src 'self'; script-src 'self' 'nonce-"+nonce+"'; style-src 'self'; "+
				"object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'self'")
		next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), ctxKey{}, nonce)))
	})
}

// Nonce returns the nonce for this response ("" outside Middleware).
func Nonce(ctx context.Context) string {
	s, _ := ctx.Value(ctxKey{}).(string)
	return s
}

Alternatives: templ, gomponents and Blade Good to know ​

In plain words: html/template checks templates at run time. Two Go libraries check them at compile time: templ (a template language that generates Go) and gomponents (HTML written as Go function calls).

Common misunderstanding: "A faster engine solves the slow page." Rendering a small page costs microseconds (see the lab); the database call costs milliseconds. Choose by safety, ergonomics and team, not by a micro-benchmark.

Definition: templ describes itself as "an HTML templating language for Go that has great developer tooling": you write .templ files, run templ generate, and get Go functions that return components, so a missing field or wrong type is a compile error. gomponents are "HTML components written in pure Go" that "render to HTML 5, and make it easy for you to build reusable components": no template files at all, so refactoring tools and the type checker work. Laravel's Blade is a compiled template language whose {{ }} echo is escaped through htmlspecialchars by default.

html/templatetemplgomponentsBlade (Laravel)
Where templates liveText files, parsed at start-up.templ files, generated to GoGo code.blade.php files, compiled to PHP and cached
Errors foundRun time (first execute)Compile timeCompile timeRun time (compiled view)
EscapingContextual (HTML, attr, URL, JS, CSS)Contextual for the parts it knows; explicit raw for the restText escaped, raw is explicithtmlspecialchars for {{ }}; raw with {!! !!}
Layoutsdefine/block + clonesComponents with childrenFunction composition@extends/@section/@yield, components, @include
Extra toolchainNonetempl CLI, editor pluginNonePHP
Learning curveSmall (stdlib)New syntaxGo onlySmall for Laravel developers
Typical teamStandard library firstLarger UI surfaces, type-safety loversGo purists, small UIsLaravel teams

Fix / how to use it: start with html/template; consider templ when the number of components and prop mismatches hurts; consider gomponents when you want no second language. The rest of this page (buffering, PRG, CSRF, flash, CSP) applies unchanged, because those live in handlers, not in templates.

Errors from the escaper: the ErrorCode list Important ​

In plain words: The escaper refuses templates whose context it cannot determine. The error tells you the template name, line and column; the fix is almost always to make the template simpler for the parser.

Common misunderstanding: "Parse succeeded, so the template is valid." Escaping runs at the first Execute, so ErrAmbigContext and ErrBranchEnd surface at the first execution, not at parse. Render every page once in a test (or at start-up) to turn them into boot failures.

Definition: *template.Error carries an ErrorCode. The documented codes: ErrAmbigContext (action in an ambiguous URL position), ErrBadHTML (malformed tag or attribute), ErrBranchEnd (if/range branches end in different contexts), ErrEndContext (the template ends inside a tag, attribute, script or comment), ErrNoSuchTemplate, ErrOutputContext (a recursive template whose output context cannot be computed), ErrPartialCharset (action inside a JS regexp character set), ErrPartialEscape (action after a backslash), ErrRangeLoopReentry (a range body ends in a different context than it began), ErrSlashAmbig (a / that could be a division or a regexp start), ErrPredefinedEscaper (Go 1.9) and ErrJSTemplate (Go 1.21; no longer returned since Go 1.22).

1  {{if .C}}/path/{{else}}/search?q={{end}}{{.X}}   in href="..."      -> ErrAmbigContext: {{.X}} appears in an ambiguous context within a URL
2  {{if .}}<a href="{{end}}x                                          -> ErrBranchEnd: {{if}} branches end in different contexts: {stateURL ...}, {stateText ...}
3  <a href = /search?q=foo>                                           -> ErrBadHTML (unquoted attribute with spaces)
4  <script>var x = [{{range .}}'{{.}},{{end}}]</script>               -> ErrRangeLoopReentry (the missing quote changes the JS state per iteration)
5  <script>alert("\{{.X}}")</script>                                  -> ErrPartialEscape
6  {{template "attrs"}} used before "attrs" is defined, inside a tag    -> ErrNoSuchTemplate

Real scenario: a conditional URL prefix with a shared suffix (line 1); an if that opens a tag in one branch and not the other (line 2); a unit test that executes every page and so catches both before deploy; a JSON-in-script island that silently depended on the safe JS subset.

CodeTypical causeFix
ErrAmbigContextAction after a conditional URL prefixMove the action inside each branch: href="{{if .C}}/path/{{.X}}{{else}}/search?q={{.X}}{{end}}"
ErrBranchEndUnbalanced tag or quote across an ifMake both branches end in the same state
ErrEndContextTemplate ends inside an open tag or attributeClose it
ErrOutputContextA recursive template whose output context cannot be computedAvoid recursion that changes context, or build the markup in Go
ErrRangeLoopReentryLoop body not self-contained in JSBuild the value as JSON in Go
ErrBadHTMLTypo in markupQuote attributes, fix the tag

Fix / how to use it: the escaping tests produce the real messages for lines 1 and 2 and assert ErrAmbigContext and ErrBranchEnd through errors.As(err, &te) on *template.Error; run them with -v to see the text.

A detail from the app test that is worth knowing: the nonce is base64 and may contain +; html/template writes it into the attribute as &#43;, the browser decodes it back, and the CSP match still works. A test that compares raw strings fails one run in a few; compare decoded values.

Mechanics ​

How the escaper works Important ​

Parse builds the ordinary text/template parse tree. The first Execute or ExecuteTemplate of a template runs the escaper over that template and the templates it calls (the traversal starts at the named template, escapeTemplate(tmpl, tmpl.text.Root, name) in escape.go): it walks each tree with a context state machine (the states show up in the error messages, for example stateText, stateURL, delimDoubleQuote and jsCtxRegexp in the ErrBranchEnd text), and rewrites every action's pipeline by appending the escaper functions named in the documentation (urlescaper, attrescaper, htmlescaper) plus the internal _html_template_* ones. It then marks the whole namespace as escaped, which freezes it. That is why:

  • Parse after the first Execute fails with html/template: cannot Parse after Execute;
  • Clone after the first Execute fails with html/template: cannot Clone "name" after it has executed;
  • escaping errors (ErrAmbigContext, ErrBranchEnd) appear at the first execute, not at parse;
  • the cost of escaping is paid once per template, not per request;
  • a named template that no execution has reached is not yet escaped: the escaping test TestFirstExecuteEscapesOnlyTheTemplatesItReaches executes a valid definition and then an unrelated definition with an ambiguous URL, which fails on its own first run. Execute every named template (every page and every fragment you serve) once at start-up or in a test.

template calls are followed: if main calls attrs inside a tag, the escaper computes the context at the call, which is why a called template that is not yet defined gives ErrNoSuchTemplate (the error.go example) and why an ordinary partial may end in a different context than it started in: the escaper propagates the computed output context to the caller (the escaping test shows a partial that opens <a href=" and a caller that closes it). ErrOutputContext is the documented failure for a recursive template, which "does not end in the same context in which it starts, and a reliable output context cannot be computed"; the exact example in the error.go comment did not fail on Go 1.27.4 in our test, so treat the code as a hint about recursion, not as something to reproduce.

The JavaScript support is a documented subset. Template actions are safe in a script when the script "consists of only declarations, assignments, literals, and calls", the action is "a standalone value, or is inside a quoted string or template literal (without ${...})", and the value is data, not "an object property key". Outside that, the doc says "escaping is best-effort and safety cannot be assured", and "incorrect escaping outside of the safe subset may be a bug but is not considered a security issue". In practice: put data into the page as JSON in a <script type="application/json"> element or as data- attributes, and read it from a static script.

Concurrency and sharing Important ​

A built template set is safe to Execute from many goroutines; the cache in this page is a map written once and read many times. Things that are not safe once the set is shared: calling Parse, Funcs, Delims, AddParseTree or Option while others execute (the first Execute has frozen the set for Parse and Clone anyway). Functions you register must be safe for concurrent use. Per-request state belongs in the data, not in a captured variable of a FuncMap closure; that is why Page carries the nonce, the CSRF token and the flash, and why the localizer in i18n is a method on the data.

Exact error and panic texts Must-know ​

The rows whose source is a test were produced by the snippets' tests on Go 1.27.4 (run with -v); the others are from the standard-library source.

SituationTextSource
Ambiguous URL positionhtml/template:t:1:51: {{.X}} appears in an ambiguous context within a URLescaping test
Branches end differentlyhtml/template:t:1:5: {{if}} branches end in different contexts: {stateURL delimDoubleQuote urlPartNone jsCtxRegexp [] attrURL elementNone <nil>}, {stateText delimNone urlPartNone jsCtxRegexp [] attrNone elementNone <nil>}escaping test
Parse after Executehtml/template: cannot Parse after Executeescaping and template.go
Clone after Executehtml/template: cannot Clone "" after it has executedinherit test
Unknown function at parsetemplate: t:1: function "upper" not definedfuncs test
Empty glob in ParseFStemplate: pattern matches no files: followed by the pattern in backquotesrender test
Bad action at parsetemplate: base.gohtml:1: missing value for ifrender test
Nil in the data pathtemplate: base.gohtml:1:39: executing "base" at <.Data.Missing.Deep>: nil pointer evaluating interface {}.Deeprender test
Body over the limithttp: request body too largeforms test
Second WriteHeaderhttp: superfluous response.WriteHeader call from ... (logged)net/http/server.go
Dangerous URL or CSS value#ZgotmplZ (URL) or ZgotmplZ (CSS) in the output, no errorescaping test
Missing map key with Option("missingkey=error")template: t:1:3: executing "t" at <.nope>: map has no entry for key "nope"funcs test

The failsafe string ZgotmplZ is a constant in escape.go (filterFailsafe = "ZgotmplZ"): it is deliberately ugly, so that a filtered value is easy to spot and search for.

Solving the classic problems ​

ProblemSymptomSolutionCost or limit
XSS from a trusted-type conversionAn attacker's tag executesSanitise, then convert in one package; grep for template.HTML(Discipline plus a sanitiser
Two pages define the same blockEvery URL shows the same pageClone the base per pageA tree copy per page
Half a page and status 200Truncated HTML, error text at the endRender into a buffer firstPage in memory
Slow pages under loadParse shows up in profilesParse once at start-upRestart to change templates
Edits need a restart in developmentSlow feedbackdev flag with os.DirFSNever use in production
Refresh re-submits a formDuplicate orders or commentsPRG with 303; idempotency key for the double clickOne more request
Typed text lost after an errorUser retypes everythingRe-render with 422 and sticky valuesForm struct
Cross-site POST changes dataForged requests succeedToken and/or CrossOriginProtectionA hidden field, a cookie
Stale CSS or JS after a deployOld styles for some usersFingerprinted names, immutableStart-up hashing
Inline script blocked by the policyConsole: CSP violationNonce on the tag, or move the script to a fileDynamic HTML
Fragment cached as a page<ul> shown as the whole pageVary: HX-Request, HX-BoostedCache split
Template error only in production500 on the first hit of one pageRender every page in a test and at start-upA test per page

Name clashes, in code ​

The inherit test TestSharedSetNameClash parses the layout, the nav and two pages into one set, renders "base" and asserts that the second page's content appears. The fix is PerPage, shown in the same package: clone the base before parsing each page.

Half-pages, in code ​

The before test and the render test are mirror images. In before, Execute(w, ...) fails after writing the first row and the response is 200 plus a truncated document plus the error text. In render, the failing execute leaves the recorder untouched, Content-Type unset and the body empty, and the handler answers 500.

Re-rendering and redirecting, in code ​

TestInvalidFormIsRerenderedWith422AndStickyValues posts a script payload in the e-mail field and asserts three things at once: the status is 422, the payload appears only in its escaped form (value="x&#34;&gt;&lt;script&gt;alert(1)&lt;/script&gt;"), and both error messages are present. TestPostRedirectGetShowsFlashOnce asserts 303 with Location: /, then a GET with the flash, then a second GET without it.

Stale assets and cached fragments, in code ​

TestHashFollowsContent (assets) shows the URL changing with the content; TestHTMXFragmentVersusFullPage (app) asserts Vary: HX-Request, HX-Boosted on the shared URL.

Choosing ​

SituationRecommendationExtra techniqueReason
Internal tool, a dozen pages, a Go teamhtml/template + embeddict partials, tests that render every pageZero dependencies, one binary
Server-rendered app with interactivityhtml/template + htmxFragments via named templates, Vary: HX-Request, HX-BoostedSmall JS, same escaping
Large UI with many components and propstemplCompile-time checks, component librariesType errors become build errors
UI authored by Go developers who dislike a second languagegomponentsFunction compositionNo template files at all
Public JSON API plus a single-page appencoding/json, no templatesStatic hosting, CSP hashesTemplates do not fit
HTML e-mailhtml/templateInline CSS at build timeHTML context
Plain-text e-mail, config files, code generationtext/templateNoneNo markup to protect
Content from users with formattingMarkdown to HTML, then a sanitiser, then template.HTML in one packagebluemonday-style allow-listThe only safe use of the typed string
Legacy PHP app being portedBlade-like layouts via clones, dict for componentsA migration checklist (PHP)Same structure, different syntax
Anonymous pages at high trafficStatic or edge-cached HTMLNo nonce (hash-based CSP), Cache-ControlPer-response nonces defeat caching

In architecture: from a single process to a distributed system ​

Monolith: one process, one database ​

The simplest correct system is the one this page builds: a single binary with embedded templates and static files, one Renderer, handlers that call the repository and render. The view lives next to the code that knows the data (the MVC view of Interaction & Presentation: MVC), there is nothing to deploy but the binary, and a request is one process: parse once at boot, execute per request, no network between the handler and the page. Sessions (or signed cookies for flash and CSRF) and the signing key are configuration. For the processes around it see net/http: Server, Client and OS Processes, Signals & Graceful Shutdown.

Modular monolith and multiple data sources ​

When teams own modules, each module ships its own templates. Two rules keep them apart. First, ParseFS names templates by file base name, so give every module its own namespace: a fs.Sub per module, one Renderer per module with its own clones, or prefixed names (billing-invoice, accounts-invoice). Second, share the look through one module that owns the layout, the partials and the FuncMap (a "ui" package), and have the others depend on it, never on each other's templates. A module that needs data from another calls its Go API (see Modular Monolith), not its database, and passes plain structs to its own templates. The Page struct is the contract between the ui module and a feature module: nonce, CSRF token, flash and one Data.

Microservices ​

A browser-facing service (a backend for frontend, see API Gateway, BFF & Service Mesh) renders HTML from several backends. Three things change. Latency: every backend call gets a deadline derived from the request context (see context), and the page degrades instead of failing: a with around an optional panel renders nothing when its data is missing. Failure: a failed call becomes a field in the page data (.Recommendations is nil), not an error that aborts the render, so one slow service does not turn into a 500; reserve the 500 for template errors. Sharing: the design system is a versioned Go module that embeds layouts, partials and fingerprinted assets, imported by every service that renders pages; services never read each other's template files. Each service validates its own forms; a distributed transaction behind a form is a saga with a status page, not a longer request (Saga).

Distributed data: replicas, caches, multi-region ​

Four failures are specific to server-rendered pages behind a load balancer.

  • Flash and CSRF across instances. A signed cookie works on every instance that shares the HMAC key and needs no sticky sessions. A server-side session needs a shared store (Redis or the database), and the flash row in the sql example above must be popped with a single DELETE ... RETURNING so two instances cannot both show it.
  • Read-your-writes after PRG. The POST writes to the primary, the 303 sends the browser to a GET that a load balancer may route to a replica that has not applied the write yet: the user saves, is redirected, and does not see the change. Pin the next read to the primary for a short window (a cookie or the flash itself carries the hint), or read from the primary on pages that follow a write (see Replication, Read Replicas & Failover).
  • HTML in caches. A CDN may cache anonymous pages and fingerprinted assets; it must not cache a page that contains a CSRF token, a flash or a personal name. Send Cache-Control: private or no-store for them, Vary: HX-Request, HX-Boosted for fragments, and public, max-age=31536000, immutable for assets (CDN, Caching). A per-response CSP nonce makes the whole page uncacheable by definition.
  • Multi-region. The signing keys must be the same (or rotated together) in every region, and the clock-independent parts of cookies (no timestamps checked without allowing skew) avoid surprises; asset hashes are identical because they come from the same build.

Scaling path: 1×, 10×, 100× ​

LoadDesignWhat to add
1×One process, parse once, buffer, PRG, signed cookiesTests that render every page; -race in CI
10×Several instances behind a load balancer; static files on a CDN; gzip in a middleware (Middlewares)Pooled buffers (already in the snippet), fragment caching for expensive widgets, ETag on pages
100×Anonymous pages cached at the edge; personalised parts as htmx fragments; read replicas for GETsHash-based CSP or no inline script (cacheable HTML), request coalescing for hot fragments, streaming with http.Flusher for very long pages
BeyondStatic generation for content pages; a rendering service separated from data servicesPre-rendering and incremental regeneration, per-region deploys

Rendering cost is almost never the first bottleneck: the benchmark below shows about 7 microseconds to render a small page from a cached set, against milliseconds for a database round trip. The things that scale badly are the ones around it: per-request parsing, uncacheable HTML and read-after-write on replicas.

Lab ​

Everything in labs 1 to 5 was run on Go 1.27.4 (darwin/arm64, Apple M4 Pro); lab 6 is expected, not run.

1. Run the whole module (real) ​

cd docs/snippets/go/templates-server-rendering/go
gofmt -l .                      # (no output)
go vet ./...                    # (no output)
go test -race -count=1 ./...
# ok  academy/templates-server-rendering/app
# ok  academy/templates-server-rendering/assets
# ok  academy/templates-server-rendering/before
# ok  academy/templates-server-rendering/csp
# ok  academy/templates-server-rendering/csrf
# ok  academy/templates-server-rendering/escaping
# ok  academy/templates-server-rendering/flash
# ok  academy/templates-server-rendering/forms
# ok  academy/templates-server-rendering/funcs
# ok  academy/templates-server-rendering/inherit
# ok  academy/templates-server-rendering/render

2. One action in eight contexts (real) ​

go test -count=1 -v -run TestEachContextEncodesDifferently ./escaping/
# html text         <p>O&#39;Reilly: &lt;i&gt;&#34;hi&#34;&lt;/i&gt; &amp; more</p>
# quoted attribute  <a title="O&#39;Reilly: &lt;i&gt;&#34;hi&#34;&lt;/i&gt; &amp; more">x</a>
# url path          <a href="/files/O%27Reilly:%20%3ci%3e%22hi%22%3c/i%3e%20&amp;%20more">x</a>
# url query         <a href="/search?q=O%27Reilly%3a%20%3ci%3e%22hi%22%3c%2fi%3e%20%26%20more">x</a>
# url whole         <a href="#ZgotmplZ">x</a>
# js string         <script>var s = "O\u0027Reilly: \u003ci\u003e\u0022hi\u0022\u003c\/i\u003e \u0026 more";</script>
# js value          <script>var v = "O'Reilly: \u003ci\u003e\"hi\"\u003c/i\u003e \u0026 more";</script>
# css value         <p style="color: ZgotmplZ">x</p>

The js string and js value lines are asserted verbatim by the test, so they are valid JavaScript: inside a JS string literal every quote and HTML-sensitive character (', ", <, >, &, /) becomes a \uXXXX escape; as a JS value the string is JSON-encoded and the same characters are escaped.

3. Watch two pages clash (real) ​

go test -count=1 -v -run TestSharedSetNameClash ./inherit/
# <html><head><title>About</title></head>
# <body><nav>ann</nav><h1>About us</h1></body></html>
# --- PASS: TestSharedSetNameClash
# (the home page was parsed first, and the about page silently replaced its "title" and "content")

4. Render errors and parse errors (real) ​

go test -count=1 -v -run 'TestExecutionError|TestParseError|TestParseFSFails' ./render/
# render broken/base: template: base.gohtml:1:39: executing "base" at <.Data.Missing.Deep>: nil pointer evaluating interface {}.Deep
# render: parse shared templates: template: base.gohtml:1: missing value for if
# render: parse shared templates: template: pattern matches no files: `partials/*.gohtml`

5. Parse once versus parse per request (real) ​

go test -run '^$' -bench . -benchmem -count=1 ./render/
# cpu: Apple M4 Pro
# BenchmarkRenderCached-12               172530     6702 ns/op     4950 B/op    136 allocs/op
# BenchmarkRenderParseEveryRequest-12     15244    78954 ns/op   138241 B/op   1977 allocs/op

About twelve times slower and fourteen times as many allocations (the count, not the bytes: 1977 vs 136 allocs/op). The second benchmark calls New, which parses the layout, the partials and all three pages, so a handler that parsed only its own page would pay less; the order of magnitude is what matters, and parsing also repeats the escaping work. Numbers are for this machine; do not quote them as universal.

6. A real server and curl (expected, not run) ​

Add main.go under a cmd/site directory of the module:

go
package main

import (
	"log"
	"log/slog"
	"net/http"
	"os"

	"academy/templates-server-rendering/app"
)

func main() {
	key := []byte(os.Getenv("SITE_KEY")) // 32 random bytes in production
	devDir := ""
	if os.Getenv("APP_ENV") == "dev" {
		devDir = "render/templates" // edit a template, refresh, see it
	}
	h, err := app.New(key, devDir, slog.Default())
	if err != nil {
		log.Fatal(err)
	}
	log.Fatal(http.ListenAndServe("127.0.0.1:8080", h))
}

Then, in two terminals (expected output, not run):

SITE_KEY=0123456789abcdef0123456789abcdef go run ./cmd/site

curl -si -c jar -b jar http://127.0.0.1:8080/contact | head -20
# HTTP/1.1 200 OK
# Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-...'; ...
# Set-Cookie: csrf_id=...; Path=/; HttpOnly; SameSite=Lax
# ... <input type="hidden" name="csrf_token" value="..."> ...

curl -si -c jar -b jar -d 'email=ann@example.test&message=hi' http://127.0.0.1:8080/contact | head -1
# HTTP/1.1 403 Forbidden        (no csrf_token)

curl -si -b jar -H 'HX-Request: true' 'http://127.0.0.1:8080/items?page=2' | sed -n '1p;/Vary/p;/<html/p'
# HTTP/1.1 200 OK
# Vary: HX-Request, HX-Boosted
# (no <html line: a fragment)

For PHP/Laravel developers ​

Blade is the closest relative, and the differences are mostly about where the work happens. Blade compiles each view to PHP once and caches the result; Go parses once at start-up and keeps the tree in memory. Blade escapes {{ }} with htmlspecialchars (its docs: "By default, Blade {{ }} statements are automatically sent through PHP's htmlspecialchars function to prevent XSS attacks") and gives you {!! !!} for raw output; Go escapes by context and gives you the typed strings for raw output, which differ in that the escaping adapts to attributes, URLs and scripts, whereas htmlspecialchars is one function for all of them.

The view, in Blade (shown as HTML because Blade is HTML plus directives):

html
{{-- resources/views/contact.blade.php: the same page as the Go snippets --}}
@extends('layouts.app')
@section('title', 'Contact')
@section('content')
  <form method="POST" action="/contact">
    @csrf
    <input name="email" value="{{ old('email') }}">
    @error('email') <span class="error">{{ $message }}</span> @enderror
    <button>Send</button>
  </form>
@endsection

The controller does what contactSubmit does: validate, redirect back with errors and old input on failure, redirect with a flash message on success.

php
// Laravel 13 controller
public function store(Request $request): RedirectResponse
{
    $request->validate([
        'email'   => ['required', 'email'],
        'message' => ['required', 'max:500'],
    ]);   // failure: redirect to the previous URL with errors and old input (JSON requests get a 422)

    // ... store or send the message here ...

    return redirect('/')->with('status', 'Thanks, we will answer soon.');   // flash, shown once
}
Laravel / BladeGo html/template
@extends('layouts.app'), @section, @yielddefine, block, template with a base cloned per page
@include('shared.errors') (parent variables are inherited)template "errors" . (only dot crosses; pass what you need)
Components with slots (<x-alert>, $slot)dict partials, or templ/gomponents components
{{ $x }} escaped, {!! $x !!} raw{{ .X }} escaped by context, template.HTML raw
@csrf, csrf_token()hidden csrf_token field, csrf.Token(ctx), or http.CrossOriginProtection (Go 1.25)
@error('field'), old('field')Form.Error("field"), Form.Value("field") (sticky values)
redirect()->with('status', ...), session()->flash(...)flash.Set before http.Redirect(..., 303)
@vite([...]) with a manifest of hashed filesassets.Path("app.css") with content hashes
trans_choice('messages.apples', 10)x/text/message or go-i18n plural rules
Vite::useCspNonce() and Vite::cspNonce()the csp middleware and Page.Nonce
php artisan view:clear after changing compiled viewsrestart (production) or dev=true reload

The Blade docs warn that an unescaped echo of user data is dangerous ("You should typically use the escaped, double curly brace syntax"); the Go equivalent of that warning is the typed strings section.

Common misconceptions ​

BeliefReality
html/template is text/template plus html.EscapeStringIt parses the template as HTML and picks an encoder per context
Using html/template makes XSS impossibletemplate.HTML, template.JS, template.URL and JavaScript outside the safe subset can reintroduce it
Parse errors show up at ParseEscaping errors (ErrBranchEnd, ErrAmbigContext) show up at the first Execute
ParseGlob on pages/*.html gives one template per pageIt gives one set; pages defining the same block overwrite each other
Template sets need a mutexA built set is safe for concurrent Execute; build before sharing
An error after Execute can still be turned into a 500Not if bytes were already written; render into a buffer first
r.Form is the request bodyIt is body plus query (body values first, so they win on a clash, but query-only keys still appear); use r.PostForm for the body
After a POST, a 302 or a 200 page is fineUse 303 (or at least a redirect) so a refresh does not re-POST
SameSite=Lax makes CSRF tokens obsoleteIt is one layer; token or Origin checking remains the standard
A CSRF token protects against XSSXSS can read the token and defeat the defence
A flash message needs a databaseA signed, short-lived cookie is enough for a sentence
?v=2 is cache bustingContent-hash file names are reliable; manual versions are forgotten
A fixed CSP nonce is fineA nonce must be new and unpredictable for every response
Every htmx request wants a fragmentBoosted requests also send HX-Request and need the full page
Faster template engines make pages fastRendering is microseconds; the database and caching rules dominate
eq is ==It is a function: all arguments are evaluated, and with several arguments it means "equal to any"

Cheat sheet ​

TopicRemember
Packagehtml/template for every page; text/template for plain text
EscapingContextual: text, attribute, URL, JS, CSS each get their own encoder, added at the first execute
Trusttemplate.HTML, JS, URL mean "I vouch"; keep them in one audited place
Files//go:embed templates, fs.Sub, ParseFS (Go 1.16); a glob that matches nothing is an error
Layoutdefine "base", block "content" ., pages only define; clone the base per page
NamesTemplates are named by file base name; one namespace per set; unique names or clones
CachingParse and escape once at start-up; executing is concurrent-safe; dev flag reloads
DataOne page struct, Data any; . is the current value, $ the root; guard nil with with
FunctionsFuncs before Parse; eq, ne, lt, printf, index, len, and, or, not
Whitespace{{- x -}} trims; the minus needs a space ({{-3}} is a number)
Partialsdict helper to pass several values; only dot crosses a template call
RenderingExecute into a buffer, then WriteHeader and buf.WriteTo(w)
FormsMaxBytesReader, ParseForm, PostForm, validate, 422 with the form and sticky values
After successhttp.Redirect(w, r, url, http.StatusSeeOther)
CSRFHidden token plus cookie (hmac.Equal), or http.CrossOriginProtection (Go 1.25); keep SameSite
FlashSigned cookie, Max-Age short, popped and expired on the next page; or a session
AssetsHash in the file name, public, max-age=31536000, immutable, serve only hashed names
htmxHX-Request: true and not HX-Boosted means fragment; send Vary: HX-Request, HX-Boosted
CSPNew random nonce per response in header and tags; no inline handlers
Go versions1.16 ParseFS, 1.18 break/continue, 1.23 else with, 1.24 range over int and funcs, 1.25 CrossOriginProtection

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — Why must a page-rendering handler import html/template rather than text/template? Must-know ​

Answer

Answer: html/template parses the template as HTML, CSS, JavaScript and URLs and adds the right encoder to every action, so a value like <script> is printed as &lt;script&gt; in text, percent-encoded in a URL and \u003c inside a script string. text/template prints values as they are, which is an XSS hole for any untrusted data. Use text/template only for plain-text output.

2 — A page shows #ZgotmplZ where a link should be. What happened? Important ​

Answer

Answer: The value sat in a URL position and failed the scheme filter (for example javascript:alert(1) or a string without an allowed protocol), so html/template replaced it with the failsafe #ZgotmplZ. Fix the data (a real https: or relative URL), or, if you control and have validated the value, pass it as template.URL.

3 — Two page files both define content, and every URL shows the same page. Why, and what is the fix? Must-know ​

Answer

Answer: All templates parsed into one *Template share one namespace, and a later definition of a name replaces an earlier one, so the last page parsed wins for every page. Parse the layout and partials once, then for each page Clone the base and parse only that page's file into the clone; clone before anything is executed.

4 — Parse succeeded, but the first request returns appears in an ambiguous context within a URL. Why so late? Important ​

Answer

Answer: Contextual escaping runs at the first Execute of a template (and the templates it calls), not at Parse. The template had an action after a conditional URL prefix, so the escaper could not tell path from query (ErrAmbigContext). Move the action inside each branch, and render every page once in a test or at start-up to turn such errors into boot failures.

5 — Why render into a bytes.Buffer instead of executing straight into the ResponseWriter? Must-know ​

Answer

Answer: A template can fail halfway (a nil pointer, a function error). If it already wrote to the ResponseWriter, the status line (200) and part of the page are sent and cannot be taken back. Rendering into a buffer first means nothing is sent on failure, so the handler can still answer 500; on success you set headers and copy the buffer.

6 — A user submits a form with an invalid e-mail. What status and body do you return, and what do you return on success? Must-know ​

Answer

Answer: On failure, re-render the same form with 422 Unprocessable Content (or 400), an error per field and the typed values kept, escaped like any other data. On success, do the work and answer 303 See Other to a GET page (Post/Redirect/Get) so refreshing cannot re-submit; a flash message can carry the confirmation.

7 — How does a hidden CSRF token stop a cross-site POST, and what does Go 1.25 add? Must-know ​

Answer

Answer: The secret is in the form and bound to a cookie; an attacker's page can cause the browser to send the cookie but cannot read the token, so the forged POST lacks a matching token and gets 403. Go 1.25 adds http.CrossOriginProtection, which rejects non-safe cross-origin browser requests using Sec-Fetch-Site or by comparing Origin and Host, with no token needed.

8 — How does a flash message survive a redirect and still show only once? Important ​

Answer

Answer: Before the redirect the handler stores the message in a short-lived, signed cookie (or a server-side session). The next page reads it, verifies the signature, shows it and expires the cookie (or deletes the session entry) in the same response, so a further request sees nothing. The signature prevents forgery; the text is still HTML-escaped when rendered.

9 — Why is template.HTML(r.FormValue("bio")) dangerous, and when is template.HTML acceptable? Must-know ​

Answer

Answer: The conversion tells the escaper the string is safe, so an attacker's <img onerror=...> is printed as markup (stored XSS). It is acceptable for developer constants and for output of a sanitiser with an allow-list, converted in one audited place. Everything else should stay a plain string.

10 — How does content-hash cache busting let you cache CSS for a year safely? Good to know ​

Answer

Answer: The file name contains a hash of its content (app.fa9a310f.css), so a change produces a new URL and the HTML references it; the old URL never changes and may be cached with immutable for a year. A manual ?v= or an unchanging name cannot give that guarantee.

11 — How should a handler serve an htmx request and a plain request on the same URL? Important ​

Answer

Answer: If HX-Request is true and HX-Boosted is not, render only the named fragment (ExecuteTemplate of the define that holds it); otherwise render the full page. Send Vary: HX-Request, HX-Boosted so caches keep the two shapes apart. Boosted requests replace the body and need the full page.

12 — What is a CSP nonce, why must it be new for every response, and why does it conflict with full-page caching? Important ​

Answer

Answer: A nonce is a random value placed in the script-src 'nonce-...' header and in the nonce attribute of allowed inline scripts; the browser runs only scripts whose nonce matches. If it were fixed or guessable, an attacker could copy it into an injected script. Because the HTML must contain this response's nonce, such a page cannot be cached and served to others; use a hash-based policy or move scripts to files for cacheable pages.

13 — What is the difference between template, block and define? Good to know ​

Answer

Answer: define names a template. template "x" . calls an existing template with the given dot (without the dot, it gets nil). block "x" . defines x with default content and calls it in place, so another file may redefine it before execution; that is how layouts expose holes.

Glossary ​

TermMeaning
html/templateStandard package that executes templates with contextual auto-escaping for HTML output
text/templateSame template language without escaping; for plain text
Contextual auto-escapingChoosing an encoder per action from its position (text, attribute, URL, JS, CSS)
EscaperThe pass at the first Execute of a template that rewrites the pipelines of it and the templates it calls
htmlescaper, attrescaper, urlescaperDocumented aliases of the internal encoders added to actions
ZgotmplZFailsafe string printed when a URL or CSS value fails its filter
template.HTMLTyped string marking a fragment as safe HTML (also JS, JSStr, CSS, URL, HTMLAttr, Srcset)
Trust boundaryThe place where unsafe data is converted to a typed safe string
ErrorCodeThe kind of an html/template error, such as ErrAmbigContext or ErrBranchEnd
ParseFSParse templates matching glob patterns from an fs.FS (Go 1.16)
embed / //go:embedCompile files into the binary as an embed.FS
fs.SubReturns an fs.FS rooted at a subdirectory
defineAction that names a template
blockdefine plus an in-place call, with default content
template (action)Calls a named template with a single value as dot
LayoutA base template with holes that pages fill
PartialA small named template included by others (nav, flash, field)
Template setThe namespace of associated templates reachable from one *Template
Name clashTwo templates with the same name in one set; the later definition wins
CloneDuplicate of a template and its set, fails after the first Execute
Template cacheParsed and escaped sets built once and reused per request
Dev-mode reloadRe-parsing templates from disk on every request during development
Dot (.)The current value inside an action
$The value passed to Execute, reachable from anywhere
PipelineChain of commands where each result feeds the next (a | f | g)
rangeLoop action with an else branch for the empty case; supports integers and functions in Go 1.24
withRebinds dot when the value is non-empty; else with in Go 1.23
FuncMapmap[string]any of functions available in templates; register before parsing
Comparison functionseq, ne, lt, le, gt, ge; eq accepts several arguments
printfAlias of fmt.Sprintf in templates
indexIndexes a map, slice or array by key or position
whitespace control {{- -}}Trim markers that remove adjacent whitespace; the minus needs a space
dictHelper that packs key-value pairs into a map so a nested template can take several values
Nested templateA template called by another, receiving one value
Render to a bufferExecuting into a bytes.Buffer and writing to the response only after success
sync.PoolReuse mechanism for buffers between requests
ParseFormParses the query and, for POST, PUT and PATCH, the body into r.Form and r.PostForm
http.MaxBytesReaderCaps a request body and returns an error beyond the limit
Sticky valuesThe user's typed input re-shown in the form after a validation error
422 Unprocessable ContentStatus for syntactically valid but semantically invalid input
PRGPost/Redirect/Get: answer a successful POST with a redirect to a GET
303 See OtherRedirect status that forces the follow-up request to be a GET
CSRFCross-site request forgery: a third-party page makes your browser send a state-changing request
CSRF tokenSecret in the form (and bound to a cookie) that an attacker cannot read
Synchronizer token patternServer-stored token compared with the one submitted
Double-submit cookieToken sent both in a cookie and in the request, compared on the server
http.CrossOriginProtectionGo 1.25 middleware rejecting non-safe cross-origin browser requests via Sec-Fetch-Site or Origin
SameSiteCookie attribute restricting when a cookie is sent on cross-site requests
Flash messageOne-shot message carried across a redirect
Signed cookieCookie whose value carries an HMAC so tampering is detected
HMACKeyed hash used to authenticate data (crypto/hmac)
i18n / pluralizationTranslating text and choosing the right plural form per language (CLDR rules)
CLDRUnicode Common Locale Data Repository, the source of plural and format rules
Cache bustingChanging a URL when its content changes so caches fetch the new file
Content hashDigest of a file's bytes used in its name
immutableCache-Control extension: the response will not change during its lifetime
htmxLibrary that swaps server-returned HTML fragments into a page via attributes like hx-get
HX-RequestHeader htmx sends on every request; always true
HX-BoostedHeader sent when the request comes from an hx-boost element
Fragment (partial rendering)A response containing only part of a page
VaryResponse header naming request headers that select the cached variant
Content-Security-PolicyResponse header listing sources the browser may load or run
NoncePer-response random value allowing specific inline scripts under CSP
strict-dynamicCSP keyword letting a trusted script load further scripts
templGo HTML templating language compiled to Go functions
gomponentsHTML components written as pure Go functions
BladeLaravel's templating engine, compiled to cached PHP
BFFBackend for frontend: a service that renders or shapes responses for one UI

References ​

Built by Morteza Negahi