Skip to main content

Overview

The mock middleware provides request mocking capabilities for testing and development, returning predefined responses for specified routes. Use it when you need:
  • API mocking for frontend development
  • Test fixtures
  • Stubbing external services

Installation

Quick Start

Configuration

Routes Map

Examples

JSON Response

Multiple Routes

With Headers

From File

Conditional Mocking

Delay Response

API Reference

Functions

Technical Details

Implementation Overview

The mock middleware is built on a thread-safe architecture using sync.RWMutex for concurrent access to mock responses. It supports both path-only and method-specific mocking patterns. Core Components:
  • Mock struct: Central registry holding mock responses with thread-safe access
  • Response matching: Two-tier matching system (method+path, then path-only)
  • Passthrough mode: Configurable behavior for unmatched requests
Request Flow:
  1. Extract request path and method from incoming request
  2. Acquire read lock for concurrent-safe access
  3. Check method-specific mocks first (methods[method][path])
  4. Fall back to path-only mocks (mocks[path])
  5. Apply default response if configured
  6. Either pass through to next handler or return 404
Response Types: The middleware provides helper functions for common response types:
  • JSON(): Marshal Go data structures to JSON with appropriate headers
  • Text(): Plain text responses
  • HTML(): HTML responses with proper content type
  • File(): Generic file responses with custom content types
  • Redirect(): HTTP redirects with location headers
  • Error(): Standardized error responses in JSON format
Thread Safety: All mock registration and retrieval operations are protected by read/write locks, making the middleware safe for concurrent use in multi-threaded environments.

Best Practices

  • Use environment variable to enable/disable
  • Keep mock data in separate files
  • Match production response structure
  • Add realistic delays for latency testing

Testing

The mock middleware includes comprehensive test coverage for all major functionality: