A fast, allowlist-based HTML sanitizer written in Go. Secure-by-default with a built-in allowlist that strips dangerous HTML content.
- Fast -- O(n) time complexity via an internal Finite State Machine
- Customizable -- modify the allowlist, add/remove tags, or disable all HTML
- Zero dependencies
Also available in Rust / npm: htmlsanitizer-rs
go get github.com/sym01/htmlsanitizersanitizedHTML, err := htmlsanitizer.SanitizeString(rawHTML)s := htmlsanitizer.NewHTMLSanitizer()
s.GlobalAttr = []string{"class"}
sanitizedHTML, err := s.SanitizeString(rawHTML)s := htmlsanitizer.NewHTMLSanitizer()
// remove <a> tag
s.RemoveTag("a")
// add a custom tag
s.AllowList.Tags = append(s.AllowList.Tags, &htmlsanitizer.Tag{
Name: "my-tag",
Attr: []string{"my-attr"},
})
sanitizedHTML, err := s.SanitizeString(rawHTML)s := htmlsanitizer.NewHTMLSanitizer()
s.AllowList = nil
sanitizedHTML, err := s.SanitizeString(rawHTML)go test ./... # run tests
go test -race ./... # with race detection
go test -bench=. -benchmem ./... # benchmarks
go test -fuzz=FuzzSanitize -fuzztime=30s . # fuzz testing