Fix FileUploadError: http: request body too large in Gin
This error occurs when a file upload exceeds the maximum body size allowed by the server. Gin defaults to a 32 MB multipart form limit. Fix it by configuring MaxMultipartMemory on the Gin engine, validating file size and type before processing, and returning descriptive error messages to the client.
Reading the Stack Trace
Here's what each line means:
- main.UploadFile(0x14000226000) /app/handlers/upload.go:15 +0x1a4: The UploadFile handler at line 15 attempts to parse a multipart form that exceeds the size limit.
- main.MaxBodySize.func1(0x14000226000) /app/middleware/bodysize.go:12 +0x98: The body-size-limiting middleware intercepts the request and enforces the maximum body size.
- github.com/gin-gonic/gin.(*Engine).handleHTTPRequest(0x14000128680, 0x14000226000): Gin dispatches the POST /api/upload request through the middleware chain and handler.
Common Causes
1. Default multipart memory too small
Gin's default MaxMultipartMemory is 32 MB. Files larger than this fail without a clear error.
func UploadFile(c *gin.Context) {
file, _ := c.FormFile("file")
c.SaveUploadedFile(file, "./uploads/"+file.Filename)
c.JSON(200, gin.H{"status": "uploaded"})
}
2. No file size validation
The handler does not check the file size before processing, allowing arbitrarily large uploads to consume memory.
func UploadFile(c *gin.Context) {
file, err := c.FormFile("file")
if err != nil {
c.String(500, err.Error())
return
}
c.SaveUploadedFile(file, "./uploads/"+file.Filename)
}
3. Missing Content-Type validation
The handler accepts any file type without checking, leading to security issues and unexpected errors when processing non-image files as images.
func UploadAvatar(c *gin.Context) {
file, _ := c.FormFile("avatar")
// No MIME type check — user could upload .exe
c.SaveUploadedFile(file, "./avatars/"+file.Filename)
}
The Fix
Set MaxMultipartMemory on the engine, validate file size and MIME type before saving, sanitize the filename with filepath.Base, and return appropriate HTTP status codes with descriptive error messages.
func UploadFile(c *gin.Context) {
file, _ := c.FormFile("file")
c.SaveUploadedFile(file, "./uploads/"+file.Filename)
c.JSON(200, gin.H{"status": "uploaded"})
}
func init() {
// Set max upload size to 10 MB
gin.DefaultWriter = os.Stdout
}
func SetupRouter() *gin.Engine {
r := gin.Default()
r.MaxMultipartMemory = 10 << 20 // 10 MB
return r
}
func UploadFile(c *gin.Context) {
file, err := c.FormFile("file")
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "file is required"})
return
}
if file.Size > 10<<20 {
c.JSON(http.StatusRequestEntityTooLarge, gin.H{"error": "file must be under 10 MB"})
return
}
allowed := map[string]bool{"image/png": true, "image/jpeg": true, "application/pdf": true}
if !allowed[file.Header.Get("Content-Type")] {
c.JSON(http.StatusBadRequest, gin.H{"error": "unsupported file type"})
return
}
dst := filepath.Join("./uploads", filepath.Base(file.Filename))
if err := c.SaveUploadedFile(file, dst); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to save file"})
return
}
c.JSON(http.StatusOK, gin.H{"status": "uploaded", "filename": file.Filename})
}
Testing the Fix
package handlers_test
import (
"bytes"
"mime/multipart"
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
)
func TestUploadFile_ValidFile(t *testing.T) {
gin.SetMode(gin.TestMode)
r := SetupRouter()
r.POST("/api/upload", UploadFile)
var buf bytes.Buffer
w := multipart.NewWriter(&buf)
part, _ := w.CreateFormFile("file", "test.png")
part.Write([]byte("fake-png-data"))
w.Close()
req := httptest.NewRequest(http.MethodPost, "/api/upload", &buf)
req.Header.Set("Content-Type", w.FormDataContentType())
rr := httptest.NewRecorder()
r.ServeHTTP(rr, req)
assert.Equal(t, http.StatusOK, rr.Code)
}
func TestUploadFile_MissingFile(t *testing.T) {
gin.SetMode(gin.TestMode)
r := SetupRouter()
r.POST("/api/upload", UploadFile)
req := httptest.NewRequest(http.MethodPost, "/api/upload", nil)
rr := httptest.NewRecorder()
r.ServeHTTP(rr, req)
assert.Equal(t, http.StatusBadRequest, rr.Code)
}
Run your tests:
go test ./handlers/... -v
Pushing Through CI/CD
git checkout -b fix/gin-file-upload-error,git add handlers/upload.go handlers/upload_test.go,git commit -m "fix: validate file size and type on upload, set MaxMultipartMemory",git push origin fix/gin-file-upload-error
Your CI config should look something like this:
name: CI
on:
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: '1.22'
- run: go mod download
- run: go vet ./...
- run: go test ./... -race -coverprofile=coverage.out
- run: go build ./...
The Full Manual Process: 18 Steps
Here's every step you just went through to fix this one bug:
- Notice the error alert or see it in your monitoring tool
- Open the error dashboard and read the stack trace
- Identify the file and line number from the stack trace
- Open your IDE and navigate to the file
- Read the surrounding code to understand context
- Reproduce the error locally
- Identify the root cause
- Write the fix
- Run the test suite locally
- Fix any failing tests
- Write new tests covering the edge case
- Run the full test suite again
- Create a new git branch
- Commit and push your changes
- Open a pull request
- Wait for code review
- Merge and deploy to production
- Monitor production to confirm the error is resolved
Total time: 30-60 minutes. For one bug.
Or Let bugstack Fix It in Under 2 minutes
Every step above? bugstack does it automatically.
Step 1: Install the SDK
go get github.com/bugstack/sdk
Step 2: Initialize
import "github.com/bugstack/sdk"
func init() {
bugstack.Init(os.Getenv("BUGSTACK_API_KEY"))
}
Step 3: There is no step 3.
bugstack handles everything from here:
- Captures the stack trace and request context
- Pulls the relevant source files from your GitHub repo
- Analyzes the error and understands the code context
- Generates a minimal, verified fix
- Runs your existing test suite
- Pushes through your CI/CD pipeline
- Deploys to production (or opens a PR for review)
Time from error to fix deployed: Under 2 minutes.
Human involvement: zero.
Try bugstack Free →No credit card. 5-minute setup. Cancel anytime.
Deploying the Fix (Manual Path)
- Run go test ./... locally to confirm the fix passes.
- Open a pull request with the upload validation changes.
- Wait for CI checks to pass on the PR.
- Have a teammate review and approve the PR.
- Merge to main and verify the deployment in staging before promoting to production.
Frequently Asked Questions
BugStack runs the fix through your existing test suite, generates upload-specific tests with various file sizes and types, and validates that the upload endpoint handles edge cases before marking it safe to deploy.
BugStack never pushes directly to production. Every fix goes through a pull request with full CI checks, so your team can review it before merging.
It depends on your use case. For avatars, 2-5 MB is typical. For document uploads, 10-50 MB. Set MaxMultipartMemory to match and validate in the handler.
For production, use object storage like S3 or GCS. Local disk storage doesn't scale across multiple instances and is lost on container restarts.