HTML Sanitizer Implementation in Go
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓HTML Sanitizer runs in O(n) time and O(n) space, in Go as in every other language.
- ✓Two different things carry the name here. html/template in the standard library is a contextual auto-escaper for templates you wrote, not a sanitizer for markup a stranger sent, and html.EscapeString only handles text.
- ✓Key the allowlist on atom.Atom rather than on the tag string: the tokenizer already interned the name, so lookup becomes an integer compare and a misspelled tag becomes a compile error instead of a silently absent entry.
- ✓The Go trap: RemoveChild sets the removed node's Parent, PrevSibling and NextSibling to nil. That is correct hygiene, and it silently destroys the loop everyone writes.
- ✓The tree is pointer-rich by construction, a heap *html.Node per token with an []Attribute beside every element, so the collector scans all of it for as long as you hold a root; escape analysis cannot stack-allocate a node that gets linked into a parent.
What HTML Sanitizer actually is
HTML Sanitizer in Go: what you actually reach for
Go implementation
package sanitize
import (
"net/url"
"strings"
"golang.org/x/net/html"
"golang.org/x/net/html/atom"
)
// Keyed on atom.Atom, not string: the tokenizer already interned the tag name.
var allowed = map[atom.Atom]map[string]bool{
atom.P: {}, atom.Em: {}, atom.Code: {}, atom.A: {"href": true, "hreflang": true},
}
var safeScheme = map[string]bool{"https": true, "mailto": true}
// Prune walks a tree from html.ParseFragment; serialize it with html.Render.
func Prune(n *html.Node) {
// RemoveChild nils out c.NextSibling. Capture the successor BEFORE removing,
// or the walk halts at the first deletion and the rest ships unsanitized.
for c := n.FirstChild; c != nil; {
next := c.NextSibling
Prune(c)
attrs, ok := allowed[c.DataAtom]
// Namespace is "" for HTML; svg and math reuse HTML tag names.
if c.Type != html.TextNode && (!ok || c.Namespace != "") {
n.RemoveChild(c)
} else if ok {
c.Attr = filter(c.Attr, attrs)
}
c = next
}
}
func filter(in []html.Attribute, allow map[string]bool) []html.Attribute {
out := in[:0] // filter in place; no second backing array
for _, a := range in {
u, err := url.Parse(strings.TrimSpace(a.Val))
if a.Namespace != "" || !allow[a.Key] || (a.Key == "href" &&
(err != nil || (u.Scheme != "" && !safeScheme[u.Scheme]))) {
continue
}
out = append(out, a)
}
return out
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Go-specific trap
Performance in Go, beyond the O(n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Go type or library should I use for HTML Sanitizer?
Two different things carry the name here. html/template in the standard library is a contextual auto-escaper for templates you wrote, not a sanitizer for markup a stranger sent, and html.EscapeString only handles text. The spec-compliant parser is golang.org/x/net/html, maintained by the Go team but outside std: Parse, ParseFragment and Render, plus a Node carrying Type, DataAtom, Namespace and Attr, with interned tag names in the companion atom package. The allowlist sanitizer built on top is github.com/microcosm-cc/bluemonday.
What is the most common Go mistake when implementing HTML Sanitizer?
RemoveChild sets the removed node's Parent, PrevSibling and NextSibling to nil. That is correct hygiene, and it silently destroys the loop everyone writes. for c := n.FirstChild; c != nil; c = c.NextSibling reads c.NextSibling after the body has already removed c, gets nil, and exits. The first disallowed element ends the sweep, and every sibling after it is rendered unsanitized. Nothing panics and no error is returned, so the function reports success on a document it barely touched. Capture next := c.NextSibling before the removal, always.
How does HTML Sanitizer actually perform in Go?
The tree is pointer-rich by construction, a heap *html.Node per token with an []Attribute beside every element, so the collector scans all of it for as long as you hold a root; escape analysis cannot stack-allocate a node that gets linked into a parent. The in-place attribute filter reuses the existing backing array, so dropping one attribute from an element allocates nothing at all. Render streams into an io.Writer, so handing it a strings.Builder or the response writer directly avoids materialising a second copy of the document. Time complexity is O(n) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialBefore paying full price for a tool, check the student deals on AI and developer tools listed on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.