Skip to main content

Overview

The feature middleware provides feature flag support for controlled rollouts, A/B testing, and gradual feature deployment. It supports static flags, in-memory providers, and custom providers.

Installation

Quick Start

Configuration

Flag Structure

Examples

Static Flags

Check Flag in Handler

Get Flag Details

Memory Provider (Dynamic)

Require Flag Middleware

Require All Flags

Require Any Flag

Custom Provider

User-Specific Flags

Percentage Rollout

List All Flags

Flag with Metadata

API Reference

Memory Provider Methods

Technical Details

Architecture

The feature middleware uses a provider-based architecture that allows flexible feature flag management:
  • Context Storage: Feature flags are stored in the request context using a private contextKey{} type for isolation
  • Provider Interface: The Provider interface defines a single method GetFlags(c *mizu.Ctx) (Flags, error) enabling custom implementations
  • Thread Safety: The MemoryProvider uses sync.RWMutex for concurrent read/write access
  • Immutable Returns: Providers return copies of flag maps to prevent external modification

Implementation Details

Flag Resolution Flow:
  1. Middleware intercepts request
  2. Provider’s GetFlags() is called with context
  3. Flags are stored in request context
  4. Helper functions (IsEnabled, Get, etc.) retrieve flags from context
  5. On provider error, empty flag map is used (fail-safe behavior)
Static Provider:
  • Wraps a Flags map in an immutable provider
  • Returns defensive copies to prevent modification
  • Zero overhead after initialization
Memory Provider:
  • Mutable in-memory flag storage
  • Uses read-write mutex for concurrent access
  • Methods: Enable(), Disable(), Toggle(), Set(), SetFlag(), Delete()
  • Safe for runtime flag updates
Middleware Functions:
  • Require(name, handler): Guards route requiring single flag
  • RequireAll(names, handler): Guards route requiring all flags enabled
  • RequireAny(names, handler): Guards route requiring at least one flag enabled
  • Custom handlers provide fallback responses when flags are disabled

Performance Characteristics

  • Static Provider: O(n) copy operation per request where n is flag count
  • Memory Provider: O(n) copy with RLock, write operations use Lock
  • Flag Lookup: O(1) map lookup from context
  • Context Storage: Single context value, minimal memory overhead

Best Practices

  • Use descriptive flag names
  • Document flag purposes
  • Clean up old flags after rollout
  • Use percentage rollouts for risky features
  • Implement a custom provider for production
  • Include metadata for analytics

Testing

The feature middleware includes comprehensive test coverage for all functionality: