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

import "github.com/go-mizu/mizu/middlewares/mock"

Quick Start

app := mizu.New()

// Mock a response
app.Use(mock.New(mock.Routes{
    "GET /api/users": mock.JSON(200, users),
}))

Configuration

Routes Map

type Routes map[string]Response

// Pattern: "METHOD /path"

Examples

JSON Response

app.Use(mock.New(mock.Routes{
    "GET /api/users": mock.JSON(200, []User{
        {ID: 1, Name: "John"},
        {ID: 2, Name: "Jane"},
    }),
}))

Multiple Routes

app.Use(mock.New(mock.Routes{
    "GET /api/users":     mock.JSON(200, users),
    "GET /api/users/1":   mock.JSON(200, user),
    "POST /api/users":    mock.JSON(201, newUser),
    "DELETE /api/users/1": mock.Status(204),
}))

With Headers

app.Use(mock.New(mock.Routes{
    "GET /api/data": mock.Response{
        Status:  200,
        Body:    `{"data": "test"}`,
        Headers: map[string]string{
            "Content-Type":  "application/json",
            "X-Custom":      "value",
        },
    },
}))

From File

app.Use(mock.New(mock.Routes{
    "GET /api/users": mock.File("testdata/users.json"),
}))

Conditional Mocking

app.Use(mock.WithOptions(mock.Options{
    Routes: mockRoutes,
    Enabled: func() bool {
        return os.Getenv("MOCK_API") == "true"
    },
}))

Delay Response

app.Use(mock.New(mock.Routes{
    "GET /api/slow": mock.Response{
        Status: 200,
        Body:   `{"data": "slow"}`,
        Delay:  2 * time.Second,
    },
}))

API Reference

Functions

// New creates mock middleware
func New(routes Routes) mizu.Middleware

// WithOptions creates with configuration
func WithOptions(opts Options) mizu.Middleware

// Response helpers
func JSON(status int, data any) Response
func Text(status int, body string) Response
func Status(status int) Response
func File(path string) Response

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:
Test CaseDescriptionExpected Behavior
TestNewCreates middleware with predefined mocksReturns mocked JSON response instead of real handler
TestMock_RegisterRegisters a mock response for a pathMock response is served for registered path
TestMock_RegisterMethodRegisters method-specific mockPOST request returns mocked response with status 201
TestMock_ClearClears all registered mocksAfter clear, real handler is called instead of mock
TestWithOptions_DefaultResponseUses default response for unmatched pathsReturns default response (503) for any unmatched path
TestJSONCreates JSON response helperResponse has correct status and JSON content type
TestTextCreates text response helperResponse contains correct text body and content type
TestHTMLCreates HTML response helperResponse has text/html content type
TestRedirectCreates redirect responseResponse has correct redirect status and Location header
TestErrorCreates error response helperReturns JSON error response with correct status
TestPrefixMocks all paths matching prefixPrefixed paths return mock, non-prefixed pass through
TestPassthroughPasses unmatched requests to next handlerReal handler is called when no mock matches