Skip to main content

Overview

The bodylimit middleware limits the size of request bodies to protect against large payload attacks and resource exhaustion. Use it when you need:
  • Protection against oversized requests
  • Memory usage control
  • Upload size limits
  • DoS attack prevention

Installation

Quick Start

Configuration

Options

Examples

Basic Limit

Custom Error Handler

Full Options

Different Limits Per Route

API vs Upload Routes

API Reference

Functions

Helper Functions

How It Works

  1. Content-Length Check: If Content-Length header exceeds limit, returns 413 immediately
  2. Body Wrapping: Wraps request body with http.MaxBytesReader
  3. Read Enforcement: If body read exceeds limit, returns error

Technical Details

Implementation

The bodylimit middleware uses a two-stage approach to enforce body size limits:
  1. Pre-flight Validation: Before processing the request, it checks the Content-Length header against the configured limit. If the header indicates the body will exceed the limit, the middleware immediately returns a 413 status code without reading the body.
  2. Runtime Enforcement: The middleware wraps the request body with http.MaxBytesReader, which enforces the limit during body reading operations. This catches cases where:
    • The Content-Length header is missing or set to -1 (unknown length)
    • The actual body size differs from the declared Content-Length
    • Chunked transfer encoding is used

Default Behavior

  • Default Limit: 1MB (1 << 20 bytes) when Limit is set to 0 or negative value
  • Default Error Response: Returns HTTP 413 (Request Entity Too Large) with plain text message
  • Body Wrapping: Uses http.MaxBytesReader to wrap the request body, which provides graceful error handling during reads

Error Handling

The middleware supports custom error handlers through the ErrorHandler option. When the limit is exceeded:
  1. If a custom ErrorHandler is configured, it is invoked with the request context
  2. Otherwise, returns default 413 response with status text

Helper Functions

The middleware provides convenient helper functions for common size units:
  • KB(n): Converts kilobytes to bytes (n × 1024)
  • MB(n): Converts megabytes to bytes (n × 1024 × 1024)
  • GB(n): Converts gigabytes to bytes (n × 1024 × 1024 × 1024)

Best Practices

  • Set appropriate limits based on expected data
  • Use smaller limits for JSON APIs
  • Use larger limits for file uploads
  • Consider user experience in error messages
  • Monitor rejected requests

Testing

The bodylimit middleware includes comprehensive test coverage for all functionality: