How It Works Features Pricing Blog Error Guides
Log In Start Free Trial
Gin · Go

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

2024/03/15 15:45:10 [GIN] 2024/03/15 - 15:45:10 | 413 | 5.204ms | 127.0.0.1 | POST /api/upload goroutine 34 [running]: runtime/debug.Stack() /usr/local/go/src/runtime/debug/stack.go:24 +0x5e main.UploadFile(0x14000226000) /app/handlers/upload.go:15 +0x1a4 github.com/gin-gonic/gin.(*Context).Next(0x14000226000) /go/pkg/mod/github.com/gin-gonic/gin@v1.9.1/context.go:174 +0x74 main.MaxBodySize.func1(0x14000226000) /app/middleware/bodysize.go:12 +0x98 github.com/gin-gonic/gin.(*Context).Next(0x14000226000) /go/pkg/mod/github.com/gin-gonic/gin@v1.9.1/context.go:174 +0x74 github.com/gin-gonic/gin.(*Engine).handleHTTPRequest(0x14000128680, 0x14000226000) /go/pkg/mod/github.com/gin-gonic/gin@v1.9.1/gin.go:620 +0x4b0

Here's what each line means:

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.

Before (broken)
func UploadFile(c *gin.Context) {
	file, _ := c.FormFile("file")
	c.SaveUploadedFile(file, "./uploads/"+file.Filename)
	c.JSON(200, gin.H{"status": "uploaded"})
}
After (fixed)
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:

  1. Notice the error alert or see it in your monitoring tool
  2. Open the error dashboard and read the stack trace
  3. Identify the file and line number from the stack trace
  4. Open your IDE and navigate to the file
  5. Read the surrounding code to understand context
  6. Reproduce the error locally
  7. Identify the root cause
  8. Write the fix
  9. Run the test suite locally
  10. Fix any failing tests
  11. Write new tests covering the edge case
  12. Run the full test suite again
  13. Create a new git branch
  14. Commit and push your changes
  15. Open a pull request
  16. Wait for code review
  17. Merge and deploy to production
  18. 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:

  1. Captures the stack trace and request context
  2. Pulls the relevant source files from your GitHub repo
  3. Analyzes the error and understands the code context
  4. Generates a minimal, verified fix
  5. Runs your existing test suite
  6. Pushes through your CI/CD pipeline
  7. 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)

  1. Run go test ./... locally to confirm the fix passes.
  2. Open a pull request with the upload validation changes.
  3. Wait for CI checks to pass on the PR.
  4. Have a teammate review and approve the PR.
  5. 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.