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

Walkthrough

Space play step click any line
Three takeaways
  1. 1Wrapping the request body in http.MaxBytesReader enforces a size cap lazily as the body is read.
  2. 2The limit only triggers an error when a handler actually reads the oversized body, so detection happens downstream.
  3. 3errors.As lets you inspect a typed error to distinguish a size-limit failure from any other read error.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Capping request body size in Gin — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code