⚠️ This repository is no longer maintained. Please use the official Gohttp.MaxBytesReaderand its example methods to limit upload file size, ensuring application security and performance. For Gin-specific usage, refer to Gin official example: limit-bytes.
Limit size of POST requests for Gin framework
When handling file uploads, it's crucial to check for middleware errors first to avoid response conflicts:
func fileUploadHandler(ctx *gin.Context) {
// Always check middleware errors FIRST
if len(ctx.Errors) > 0 {
// Size limiter has already sent HTTP 413 response
return
}
// Safe to process file upload
if file, err := ctx.FormFile("file"); err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{
"error": "Failed to process file: " + err.Error(),
})
} else {
ctx.JSON(http.StatusOK, gin.H{
"success": true,
"filename": file.Filename,
"size": file.Size,
})
}
}func badHandler(ctx *gin.Context) {
// Wrong: This will cause response conflicts
if file, err := ctx.FormFile("file"); err != nil {
ctx.JSON(http.StatusOK, gin.H{"msg": "fail: " + err.Error()})
} else {
ctx.JSON(http.StatusOK, gin.H{"msg": "ok: " + file.Filename})
}
}When a request exceeds the size limit, the middleware will:
- Add an error to
ctx.Errors - Set
Connection: closeheader - Return HTTP 413 (Request Entity Too Large) status
- Send JSON response:
{"error":"request too large"} - Call
ctx.Abort()to prevent further processing
- Always check
ctx.Errorsfirst in your handlers - Use realistic size limits (consider multipart overhead)
- Handle HTTP 413 responses properly on the client side
- Test both normal and oversized file uploads
r.Use(limits.RequestSizeLimiter(1024)) // 1KB
r.Use(limits.RequestSizeLimiter(1024 * 1024)) // 1MB
r.Use(limits.RequestSizeLimiter(10 * 1024 * 1024)) // 10MBIf you're experiencing duplicate JSON responses like:
{"error":"request too large"}{"msg":"fail: HTTP request too large"}This happens when your handler tries to send a response after the middleware has already sent one. Solution: Always check ctx.Errors first!
fetch("/upload", {
method: "POST",
body: formData,
})
.then((response) => {
if (response.status === 413) {
alert("File too large, please select a smaller file");
return;
}
return response.json();
})
.then((data) => {
console.log("Upload successful:", data);
});See the _example/ directory for complete working examples:
_example/main.go- File upload best practices