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.
Code
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, "<script>") {
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
CSP Header BuilderBuild a Content-Security-Policy header from per-directive sources, skipping empty ones and rejecting a blanket wildcard.HTML Entity Encoder / DecoderEncode the five HTML-significant characters and decode named or numeric entities, with optional numeric encoding for non-ASCII text.Regex Escape GeneratorEscape plain text so it can be embedded safely in a JavaScript RegExp, covering all metacharacters like dots, brackets, braces, and backslashes.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.