sanitize

package
v5.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 28, 2026 License: MIT Imports: 5 Imported by: 0

Documentation

Overview

Package sanitize provides HTML sanitization that strips XSS vectors while preserving safe formatting and structure markup.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Sanitize

func Sanitize(parseHTML string, parseOptions ...Policy) string

Sanitize parses parseHTML and returns an XSS-safe HTML string. The first element of parseOptions, if provided, is used as the sanitization policy; otherwise DefaultPolicy is applied.

Example

ExampleSanitize strips dangerous markup and URL schemes while keeping safe formatting and allowlisted links.

package main

import (
	"fmt"

	"github.com/monstercameron/GoWebComponents/v5/sanitize"
)

func main() {
	parseDirty := `<p>Hello <strong>world</strong></p>` +
		`<a href="javascript:alert(1)">x</a>` +
		`<a href="https://example.test">ok</a>` +
		`<img src=x onerror=alert(1)>` +
		`<script>alert(1)</script>`
	fmt.Println(sanitize.Sanitize(parseDirty))
}
Output:
<p>Hello <strong>world</strong></p><a>x</a><a href="https://example.test">ok</a><img src="x">

Types

type Policy

type Policy struct {
	// AllowedTags is the set of element names that may appear in output.
	AllowedTags map[string]bool
	// AllowedAttributes is the set of attribute names that may appear in output.
	AllowedAttributes map[string]bool
	// AllowedURLSchemes is the set of scheme names (e.g. "https") allowed in
	// URL-bearing attributes. Relative and fragment URLs are always allowed.
	AllowedURLSchemes map[string]bool
}

Policy defines the allowlist for HTML sanitization. Tags, attributes, and URL schemes outside these sets are stripped or unwrapped.

A Policy's maps are only ever READ during Sanitize, so one Policy may be shared across concurrent Sanitize calls — but callers must treat a shared Policy as immutable: mutating its maps (e.g. AllowedURLSchemes["data"]=true) while another goroutine sanitizes is a data race. Build the Policy fully before sharing it.

func DefaultPolicy

func DefaultPolicy() Policy

DefaultPolicy returns a safe allowlist covering common formatting and document-structure elements without permitting script execution vectors.

func (Policy) Sanitize

func (parsePolicy Policy) Sanitize(parseHTML string) string

Sanitize parses parseHTML and returns an XSS-safe HTML string using the receiver policy as the allowlist.

Sanitize fails closed: any parse error (including input nested deeper than x/net/html's 512-node open-element-stack cap) yields "" rather than leaking raw input. It imposes no input-size ceiling of its own, so callers exposing it to untrusted request bodies should cap the body size upstream.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL