Skip to main content

Overview

The version middleware provides API versioning support through headers, query parameters, or URL path prefixes. It helps manage multiple API versions and handles deprecation warnings.

Installation

Quick Start

Configuration

Examples

Version from Header

Client request:

Version from Query Parameter

Request: GET /users?api_version=v2

Version from URL Path

Supported Versions Only

Deprecation Warnings

Using Helper Functions

Version-Specific Routes

Content Negotiation

Feature Flags by Version

API Reference

Version Detection Order

When multiple sources are configured:
  1. Header (e.g., Accept-Version: v2)
  2. Query parameter (e.g., ?version=v2)
  3. Path prefix (e.g., /v2/users)
  4. Default version

Response Headers

For deprecated versions:

Technical Details

Architecture

The version middleware uses a context-based approach to store and retrieve version information:
  1. Version Detection: The middleware examines multiple sources in a specific priority order
  2. Context Storage: Detected version is stored in the request context using a private context key
  3. Validation: Optional validation against supported/deprecated version lists
  4. Header Injection: Automatic deprecation headers for deprecated versions

Implementation Details

Version Detection Priority:
  1. HTTP Header (configurable, default: Accept-Version)
  2. Query Parameter (configurable, default: version)
  3. Path Prefix (optional, pattern: /v{number}/...)
  4. Default Version (fallback)
Version String Validation:
  • Pattern: v or V followed by digits and optional dots
  • Examples: v1, v2, V1, v1.0, v1.2.3
  • Invalid: api, empty string, v, va
Context Management:
  • Uses a private contextKey{} struct to prevent collisions
  • Version stored as string in request context
  • Retrieved via GetVersion(c) or Get(c) helper functions
Performance Optimizations:
  • Supported and deprecated versions stored in maps for O(1) lookup
  • Single pass through version sources with early exit
  • No regex matching for version strings (character-by-character validation)

Response Headers

For deprecated versions, the middleware automatically adds:
  • Deprecation: true - Indicates the version is deprecated
  • Sunset: See documentation for migration guide - Migration information

Best Practices

  • Always set a default version
  • Document supported versions
  • Add deprecation warnings before removal
  • Use semantic versioning (v1, v2, v3)
  • Maintain backward compatibility within major versions
  • Provide migration guides for deprecated versions

Testing

The middleware includes comprehensive test coverage for all features: