Skip to main content

Overview

The maintenance middleware enables maintenance mode for your application, returning a 503 Service Unavailable response with optional whitelist support for IPs and paths.

Installation

Quick Start

Configuration

Examples

Basic Maintenance Mode

Custom Message

Custom Handler

Whitelist IPs

Whitelist Paths

Dynamic Control

Toggle Maintenance

Scheduled Maintenance

Check Function

Environment-Based

With Retry-After

JSON Response

API Reference

Response Headers

Technical Details

Implementation Architecture

The maintenance middleware is implemented with a layered approach for flexibility and performance:
  1. Static Configuration - Uses Options struct to configure enabled state, messages, status codes, and retry headers
  2. Dynamic Mode Control - Mode type provides thread-safe atomic operations for runtime enable/disable toggling
  3. Bypass Mechanisms - Implements two bypass layers:
    • IP-based whitelisting via Whitelist option (checks X-Forwarded-For, X-Real-IP, and RemoteAddr)
    • Path-based whitelisting via WhitelistPaths option (exact path matching)
  4. Custom Check Function - Supports dynamic maintenance state via Check function, which takes precedence over static Enabled flag
  5. Scheduled Maintenance - Uses time-based checks to automatically enable/disable maintenance during specific windows

Key Components

  • Options: Configuration struct with fields for enabled state, messages, status codes, handlers, and whitelists
  • Mode: Thread-safe maintenance mode controller using atomic.Int32 for concurrent read/write operations
  • WithOptions: Core middleware factory that processes configuration and returns the middleware function
  • ScheduledMaintenance: Helper function that creates time-windowed maintenance middleware
  • getClientIP: Helper function to extract client IP from various headers (X-Forwarded-For, X-Real-IP, RemoteAddr)
  • itoa: Custom integer-to-string conversion for Retry-After header (avoids fmt package overhead)

Execution Flow

  1. Check if maintenance is enabled (via Check function or Enabled flag)
  2. If disabled, pass request to next handler
  3. If enabled, check IP whitelist (bypass if matched)
  4. Check path whitelist (bypass if matched)
  5. Execute custom handler if provided, or return default 503 response with Retry-After header

Thread Safety

The Mode type uses atomic operations for thread-safe state management:
  • Enable() and Disable() use atomic.StoreInt32
  • IsEnabled() uses atomic.LoadInt32
  • Toggle() uses atomic.CompareAndSwapInt32 for lock-free toggling

Best Practices

  • Whitelist health check endpoints for monitoring
  • Use scheduled maintenance for planned downtime
  • Whitelist admin IPs for debugging
  • Set appropriate Retry-After values
  • Provide helpful maintenance messages
  • Use dynamic control for emergency maintenance

Testing

The maintenance middleware includes comprehensive test coverage for all scenarios: