go
27 lines · 5 steps
Capping request body size in Gin
A Gin middleware that limits request body size and a helper that turns the overflow error into a clean 413 response.
Explained by
highlit
1package middleware
2
3import (
4 "errors"
5 "net/http"
6
7 "github.com/gin-gonic/gin"
8)
9
10func MaxBodySize(limit int64) gin.HandlerFunc {
11 return func(c *gin.Context) {
12 c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, limit)
13 c.Next()
14 }
15}
16
17func HandleBodyTooLarge(c *gin.Context, err error) bool {
18 var maxErr *http.MaxBytesError
19 if errors.As(err, &maxErr) {
20 c.AbortWithStatusJSON(http.StatusRequestEntityTooLarge, gin.H{
21 "error": "request body too large",
22 "limit": maxErr.Limit,
23 })
24 return true
25 }
26 return false
27}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Wrapping the request body in http.MaxBytesReader enforces a size cap lazily as the body is read.
- 2The limit only triggers an error when a handler actually reads the oversized body, so detection happens downstream.
- 3errors.As lets you inspect a typed error to distinguish a size-limit failure from any other read error.
Related explainers
python
import logging import uuid from contextvars import ContextVar
Request ID tracing in FastAPI middleware
middleware
context-variables
request-tracing
Intermediate
7 steps
php
<?php namespace App\Http\Middleware;
Idempotency keys in Laravel middleware
idempotency
middleware
caching
Advanced
8 steps
ruby
class PaymentGateway class MissingCredentialError < StandardError; end def initialize(env: Rails.env)
Wrapping Rails credentials in a gateway
encapsulation
credentials
error handling
Intermediate
6 steps
go
package batch import "fmt"
Splitting a slice into batches in Go
generics
slices
error-handling
Intermediate
6 steps
rust
use axum::{ extract::{Request, State}, http::{HeaderValue, StatusCode}, middleware::Next,
API version headers with Axum middleware
middleware
http-headers
versioning
Intermediate
8 steps
javascript
function escapeHtml(str) { return str.replace(/[&<>"']/g, (ch) => ({ '&': '&', '<': '<',
Safely highlighting search matches in text
html-escaping
regex
search-highlighting
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/capping-request-body-size-in-gin-explained-go-2d2f/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.