Skip to main content

Overview

The vary middleware manages the Vary HTTP header, telling caches which request headers affect response content. Use it when you need:
  • Proper cache control
  • Content negotiation
  • CDN configuration

Installation

Quick Start

Configuration

Options

Examples

Single Header

Multiple Headers

Common Patterns

API Reference

Functions

Technical Details

Implementation Overview

The vary middleware manages the Vary HTTP response header by:
  1. Header Management: Maintains a set of headers that affect response content
  2. Duplicate Prevention: Uses case-insensitive comparison to prevent duplicate headers
  3. Header Merging: Combines new Vary headers with existing ones from the response
  4. Execution Order: Processes after the handler executes to capture all Vary requirements

Key Functions

add(c *mizu.Ctx, headers ...string)

  • Adds headers to the Vary response header
  • Parses existing Vary header and creates a set for deduplication
  • Uses case-insensitive comparison (strings.ToLower)
  • Joins headers with comma-space separator

autoDetect(c *mizu.Ctx)

  • Automatically detects content negotiation headers from the request
  • Checks for: Accept, Accept-Encoding, Accept-Language
  • Only adds headers that are present in the request

Options Structure

Convenience Functions

The middleware provides several preset functions:
  • AcceptEncoding(): Adds Accept-Encoding to Vary
  • Accept(): Adds Accept to Vary
  • AcceptLanguage(): Adds Accept-Language to Vary
  • Origin(): Adds Origin to Vary (useful for CORS)
  • All(): Adds common headers: Accept, Accept-Encoding, Accept-Language
  • Auto(): Enables automatic header detection

Best Practices

  • Include all headers that affect response
  • Use with compression middleware
  • Consider CDN caching implications
  • Don’t over-vary (reduces cache effectiveness)

Testing

The middleware includes comprehensive tests covering various scenarios: