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
go
package streaming import ( "bufio"
Streaming NDJSON logs over HTTP in Go
http-streaming
channels
select
Advanced
10 steps
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 steps
go
package api import ( "crypto/sha256"
ETag conditional requests in Gin
http-caching
etag
conditional-requests
Intermediate
6 steps
go
func (w *Watcher) resetDebounce(d time.Duration) { if !w.timer.Stop() { select { case <-w.timer.C:
Debouncing a stream of events in Go
debounce
timers
channels
Advanced
7 steps
java
public static Map<String, String> parseCookieHeader(String header) { Map<String, String> cookies = new LinkedHashMap<>(); if (header == null || header.isBlank()) { return cookies;
Parsing an HTTP Cookie header in Java
string-parsing
http
url-decoding
Intermediate
6 steps
go
package logging import ( "context"
Deduplicating log attributes in Go's slog
decorator-pattern
structured-logging
immutability
Intermediate
8 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.