sanitize

package
v4.2.0 Latest Latest
Warning

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

Go to latest
Published: Jul 5, 2026 License: MIT Imports: 4 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/v4/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.

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.

Jump to

Keyboard shortcuts

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