Render User Data with Contextual HTML Escaping

Render untrusted names, bodies, and links through html/template so contextual escaping blocks script injection and bad URLs.

GoSecurity Boundaries

Code

gosnippet
43 lines
package main

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

type Comment struct {
	Author string
	Body   string
	Link   string
}

func main() {
	page := template.Must(template.New("comment").Parse(
		`<article><h2>{{.Author}}</h2><p>{{.Body}}</p><a href="{{.Link}}">profile</a></article>`,
	))
	comment := Comment{
		Author: "<b>Mallory</b>",
		Body:   `<script>alert("x")</script>`,
		Link:   "javascript:alert(1)",
	}

	var output bytes.Buffer
	if err := page.Execute(&output, comment); err != nil {
		panic(err)
	}
	rendered := output.String()
	fmt.Println(rendered)

	if strings.Contains(rendered, "<script>") {
		panic("script tag was not escaped")
	}
	if !strings.Contains(rendered, "&lt;script&gt;") {
		panic("expected escaped body text")
	}
	if !strings.Contains(rendered, "#ZgotmplZ") {
		panic("expected dangerous URL to be blocked")
	}
}

What the code does

Count the function main as the entire surface area of Render User Data with Contextual HTML Escaping.

Every err != nil branch (1 site) calls panic(err) — the run stops at the first failure instead of continuing in a broken state.

Watch out for

  • Failures abort via panic(err) — nothing is returned for the caller to check, and nothing in the snippet recovers.

Statements that matter most here

panic("expected dangerous URL to be blocked")
panic("script tag was not escaped")
panic("expected escaped body text")

Interactive Tools for This Topic

FAQ

How does the code signal failure?
Through `panic(err)` — the 1 checkpoints test `err` and abort the run on the first non-nil one.
How do you run Render User Data with Contextual HTML Escaping?
The file is self-contained: run it directly, no dependencies to install beforehand.