HTML from templates

A handler that answers HTML parses a template once and executes it per request. html/template escapes every value for the place it lands in, so a page that shows a user's name is safe by default; a layout is a second template that the first one calls. This lesson serves the pages through httptest, so the body printed below is the exact HTML a browser would receive.

A page from a template

The template writes a heading and a list. The handler passes a struct and the template walks it, and the response is HTML with no content type set by the handler: the server sniffs the first bytes and sends text/html; charset=utf-8. The client reads the body as text.

package main import ( "fmt" "html/template" "io" "net/http" "net/http/httptest" ) type Page struct { Title string Items []string } func main() { tmpl := template.Must(template.New("page").Parse(`<h1>{{.Title}}</h1><ul>{{range .Items}}<li>{{.}}</li>{{end}}</ul>`)) mux := http.NewServeMux() mux.HandleFunc("GET /", func(w http.ResponseWriter, r *http.Request) { data := Page{Title: "Notes", Items: []string{"one", "two"}} if err := tmpl.Execute(w, data); err != nil { http.Error(w, "render failed", http.StatusInternalServerError) } }) srv := httptest.NewServer(mux) defer srv.Close() resp, err := http.Get(srv.URL + "/") if err != nil { panic(err) } body, _ := io.ReadAll(resp.Body) resp.Body.Close() fmt.Println("status:", resp.Status) fmt.Print("body: ", string(body)) }

go build -o app main.go && ./app

status: 200 OK
body: <h1>Notes</h1><ul><li>one</li><li>two</li></ul>

The page has no newline between the tags because the template has none. A template in a real project lives in a file and is parsed at start-up with template.ParseFiles or template.ParseFS over an embed.FS; the handler is the same line of code.

A layout and a body

define names a template inside the file, and template calls it. A layout defines the page around a body, and the handler executes the layout by name. One file can hold the layout, the page and a partial that both pages use, which is how a site keeps its header in one place.

package main import ( "fmt" "html/template" "io" "net/http" "net/http/httptest" ) const page = `{{define "layout"}}<html><body>{{template "body" .}}</body></html>{{end}}{{define "body"}}<p>{{.}}</p>{{end}}` func main() { tmpl := template.Must(template.New("page").Parse(page)) mux := http.NewServeMux() mux.HandleFunc("GET /", func(w http.ResponseWriter, r *http.Request) { if err := tmpl.ExecuteTemplate(w, "layout", "hello"); err != nil { http.Error(w, "render failed", http.StatusInternalServerError) } }) srv := httptest.NewServer(mux) defer srv.Close() resp, err := http.Get(srv.URL + "/") if err != nil { panic(err) } body, _ := io.ReadAll(resp.Body) resp.Body.Close() fmt.Print("body: ", string(body)) }

go build -o app main.go && ./app

body: <html><body><p>hello</p></body></html>

ExecuteTemplate is Execute with a name, and the dot passes the same data down. A site with several pages defines a layout once and a body per page, parses them together so the names cannot collide, and executes the layout for each request.

Escaping user input

The value below looks like HTML and arrives as data. The template puts it in a paragraph, and html/template escapes the tags and the ampersand, so the browser shows the text instead of rendering it. The same call with text/template would have produced a bold sentence, which is what an attacker wants.

package main import ( "fmt" "html/template" "io" "net/http" "net/http/httptest" ) func main() { tmpl := template.Must(template.New("page").Parse(`<p>{{.}}</p>`)) mux := http.NewServeMux() mux.HandleFunc("GET /", func(w http.ResponseWriter, r *http.Request) { value := `<b>bold</b> & <i>italic</i>` if err := tmpl.Execute(w, value); err != nil { http.Error(w, "render failed", http.StatusInternalServerError) } }) srv := httptest.NewServer(mux) defer srv.Close() resp, err := http.Get(srv.URL + "/") if err != nil { panic(err) } body, _ := io.ReadAll(resp.Body) resp.Body.Close() fmt.Print("body: ", string(body)) }

go build -o app main.go && ./app

body: <p>&lt;b&gt;bold&lt;/b&gt; &amp; &lt;i&gt;italic&lt;/i&gt;</p>

Every angle bracket and the ampersand became an entity, and the browser renders the tags as text. A value in an attribute, a URL or a script gets the escape that place needs, which is the contextual part of the package. A program that needs to render trusted HTML uses template.HTML, and that type is the one place to look when a page shows tags it should not.

A template that does not fit its data

The template asks for a field the data does not have. Execution fails partway, so the handler below renders into a buffer first and only writes the page when the render succeeded; the error goes to the log and the client gets a clean 500. Rendering straight into w would have sent half a page and then a second status line.

package main import ( "bytes" "fmt" "html/template" "io" "net/http" "net/http/httptest" ) func main() { tmpl := template.Must(template.New("page").Parse(`<p>{{.Name}}</p>`)) mux := http.NewServeMux() mux.HandleFunc("GET /", func(w http.ResponseWriter, r *http.Request) { var buf bytes.Buffer if err := tmpl.Execute(&buf, struct{ Title string }{Title: "notes"}); err != nil { fmt.Println("execute error:", err) http.Error(w, "render failed", http.StatusInternalServerError) return } w.Write(buf.Bytes()) }) srv := httptest.NewServer(mux) defer srv.Close() resp, err := http.Get(srv.URL + "/") if err != nil { panic(err) } body, _ := io.ReadAll(resp.Body) resp.Body.Close() fmt.Println("status:", resp.Status) fmt.Print("body: ", string(body)) }

go build -o app main.go && ./app

execute error: template: page:1:5: executing "page" at <.Name>: can't evaluate field Name in type struct { Title string }
status: 500 Internal Server Error
body: render failed

The error names the template, the position and the type, and the buffer kept the page out of the response. A handler that renders many pages pays for the buffer; a large page can write to w after a bytes.Buffer check of the data instead, and the trade is memory against atomicity.

Templates in a service

Parse templates once at start-up, keep them in the handler struct, and set Content-Type to text/html; charset=utf-8 explicitly rather than trusting the sniffing. A page that must be cacheable sends an ETag or a Cache-Control; a page that is per request sends Cache-Control: no-store, because a shared cache that stores a personalised page serves it to the next visitor. And a form page includes a hidden token, which is the CSRF protection the cookie alone does not give.

The HTML in the capstone service is one page that the embedded frontend replaces, and the next lesson stops the server without cutting a request in half.

Exercises

  1. Change the escaping example to text/template and read the body. Which line of the output changes, and what would the browser do with it?
  2. Add a second body template and a second route that executes it. How many templates does the parsed set hold, and how does ExecuteTemplate choose one?
  3. Put the value in an attribute, as in <a href="{{.}}">, and pass javascript:alert(1). What does the escaper do, and why is that not the same escape as a paragraph?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does html/template do with a value in a paragraph?

    Answer

    Escapes the HTML characters

    The escape depends on where the value lands.

  2. What does define create?

    Answer

    A named template inside the set

    template calls it by name.

  3. What does ExecuteTemplate take that Execute does not?

    Answer

    The name of the template to run

    A set can hold several templates.

  4. Why render into a buffer before writing the response?

    Answer

    A failed execute must not send half a page

    The status goes out with the first byte.

  5. What content type does the server sniff for a page?

    Answer

    text/html; charset=utf-8

    Set it explicitly in a real service.

  6. When does a template execute fail?

    Answer

    When the data lacks a field the template reads

    A parse error is a different failure.

  7. What is template.HTML for?

    Answer

    Marking a value as trusted HTML that needs no escape

    It is the one place a page can inject markup.

  8. Why parse templates at start-up?

    Answer

    A parse error fails at boot, not in a request

    The set is immutable afterwards.

  9. What does Cache-Control: no-store mean?

    Answer

    A shared cache must not keep the page

    A personalised page must not be served to another user.

  10. What does the escaping depend on?

    Answer

    The context where the value appears

    Attribute, URL and script need different escapes.

The code on this page was run with go 1.26.10 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev

Banner image