Skip to main content

Overview

The sanitizer middleware sanitizes request data to prevent XSS, SQL injection, and other injection attacks. Use it when you need:
  • XSS prevention
  • Input cleaning
  • Data normalization

Installation

Quick Start

Configuration

Options

Examples

Default Sanitization

Strip HTML

Escape Instead of Strip

Specific Fields

Custom Sanitizer

API Reference

Functions

What Gets Sanitized

  • Query parameters
  • Form data
  • JSON body fields
  • Path parameters

Technical Details

The sanitizer middleware operates by intercepting HTTP requests and applying configurable sanitization rules to input data before it reaches your handlers.

Implementation Overview

The middleware processes request data in the following order:
  1. Query Parameters: Sanitizes all URL query parameters
  2. Form Data: For POST/PUT/PATCH requests, sanitizes both r.Form and r.PostForm fields
  3. Field Filtering: Applies whitelist (Fields) or blacklist (Exclude) filtering

Sanitization Pipeline

Each value passes through a configurable pipeline of operations:
  1. Trim Spaces (TrimSpaces): Removes leading and trailing whitespace using strings.TrimSpace
  2. Strip Non-Printable (StripNonPrintable): Removes non-printable characters while preserving newlines, carriage returns, and tabs
  3. Strip Tags (StripTags): Removes HTML tags using regex-based matching:
    • First removes <script> and <style> tags with their contents
    • Then removes all remaining HTML tags
  4. HTML Escape (HTMLEscape): Converts special characters to HTML entities using html.EscapeString
  5. Max Length (MaxLength): Truncates values exceeding the specified length

Key Functions

  • shouldSanitize(): Determines if a field should be sanitized based on Fields and Exclude lists
  • sanitizeValue(): Applies the sanitization pipeline to a single value
  • stripNonPrintable(): Uses unicode.IsPrint() to filter characters
  • stripTags(): Uses compiled regex patterns for efficient HTML tag removal

Performance Considerations

  • Field and exclude maps are pre-built at middleware initialization for O(1) lookups
  • Regex patterns for tag stripping are compiled once and reused
  • The middleware modifies request objects in-place to avoid allocations

Best Practices

  • Use as defense in depth
  • Don’t rely solely on sanitization
  • Use parameterized queries for SQL
  • Use proper output encoding

Testing

Test Coverage

The sanitizer middleware includes comprehensive test cases covering all functionality: