Gin foundations · 5 MIN READ
File uploads in Gin: cap the request, sniff the bytes and never let the client name the file
Accept a multipart upload in Gin with a hard size cap, decide its type from its content, generate the storage name yourself and test it with a request built by mime/multipart.
An upload is attacker-controlled bytes wrapped in attacker-controlled labels. The filename, the declared Content-Type and the size all come from the client, and so does the number of parts. c.FormFile makes accepting a file one line long, which is exactly why the limits, the type decision and the storage name have to be written deliberately around it.
gin · A MAP OF THE IDEA
- Cap with MaxBytesReader
- Check per-file size
- Sniff and allowlist
- Store under own name
Useful when
- Type decisions rest on content, not on client labels.
- Generated names remove traversal, collision and overwrite risks.
Watch out
- FormFile reads the whole body before you can inspect the file.
- Sniffing checks signatures only; images still need decoding limits.
Implementation & operation cost: A size cap, a 512-byte sniff and a hash pass per upload, plus a streaming path once files get large.
What goes wrong with a naive upload handler
A handler that calls c.FormFile and then c.SaveUploadedFile(file, "uploads/"+file.Filename) has four separate bugs. Nothing bounds the request, so one client can fill memory or the temp directory. The declared type is trusted, so an HTML page labeled image/png can be served back from your origin and run script there. The client's name decides where the file lands, so uploads overwrite each other or land somewhere unexpected. And SaveUploadedFile creates the parent directory and, in v1.12.0, also chmods it to 0o750 on every call, which can surprise an operator who set permissions on a shared directory.
An avatar endpoint and the requests that probe it
The program accepts an avatar, enforces a request cap and a per-file cap, sniffs the first 512 bytes, derives the extension from an allowlist and names the file after its SHA-256. main sends seven requests: six built with mime/multipart, the same encoding a browser uses, including files that lie about their type, and one that is not multipart at all.
package main
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"io"
"mime/multipart"
"net/http"
"net/http/httptest"
"net/textproto"
"github.com/gin-gonic/gin"
)
const (
maxRequestBytes = 8 << 10 // whole multipart body; tiny so the demo can exceed it
maxFileBytes = 4 << 10
)
// allowed maps a sniffed type to the only extension we will ever store.
var allowed = map[string]string{"image/png": ".png", "image/jpeg": ".jpg", "image/gif": ".gif", "image/webp": ".webp"}
func uploadAvatar(c *gin.Context) {
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, maxRequestBytes)
fh, err := c.FormFile("avatar")
if err != nil {
var tooLarge *http.MaxBytesError
switch {
case errors.As(err, &tooLarge):
c.JSON(http.StatusRequestEntityTooLarge, gin.H{"error": "request exceeds 8 KiB"})
case errors.Is(err, http.ErrMissingFile):
c.JSON(http.StatusBadRequest, gin.H{"error": "avatar file is required"})
default:
c.JSON(http.StatusBadRequest, gin.H{"error": "expected multipart/form-data"})
}
return
}
if fh.Size > maxFileBytes {
c.JSON(http.StatusRequestEntityTooLarge, gin.H{"error": "avatar exceeds 4 KiB"})
return
}
f, err := fh.Open()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "cannot read upload"})
return
}
defer f.Close()
head := make([]byte, 512)
n, _ := io.ReadFull(f, head) // a short file is fine: sniff what we got
kind := http.DetectContentType(head[:n])
ext, ok := allowed[kind]
if !ok {
c.JSON(http.StatusUnsupportedMediaType, gin.H{"error": "unsupported file type", "detected": kind})
return
}
if _, err := f.Seek(0, io.SeekStart); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "cannot read upload"})
return
}
sum := sha256.New()
if _, err := io.Copy(sum, f); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "cannot read upload"})
return
}
name := hex.EncodeToString(sum.Sum(nil))[:24] + ext
// A real service now streams f to object storage under name.
c.JSON(http.StatusCreated, gin.H{"stored_as": name, "bytes": fh.Size, "type": kind, "original": fh.Filename})
}
// multipartBody builds the request a browser would send for <input type=file>.
func multipartBody(field, filename, declaredType string, content []byte) (*bytes.Buffer, string) {
var buf bytes.Buffer
mw := multipart.NewWriter(&buf)
must(mw.SetBoundary("lesson-boundary-0123456789"))
must(mw.WriteField("caption", "profile picture"))
if field != "" {
h := make(textproto.MIMEHeader)
h.Set("Content-Disposition", fmt.Sprintf(`form-data; name=%q; filename=%q`, field, filename))
h.Set("Content-Type", declaredType) // the client's claim; the handler ignores it
part, err := mw.CreatePart(h)
must(err)
_, err = part.Write(content)
must(err)
}
must(mw.Close())
return &buf, mw.FormDataContentType()
}
func must(err error) {
if err != nil {
panic(err)
}
}
func main() {
gin.SetMode(gin.TestMode)
r := gin.New()
r.MaxMultipartMemory = 1 << 20 // in-memory threshold for file parts, not a size limit
r.POST("/avatars", uploadAvatar)
png := append([]byte("\x89PNG\r\n\x1a\n"), bytes.Repeat([]byte{0}, 56)...)
cases := []struct {
field, filename, declared string
content []byte
}{
{"avatar", "../../avatar.png", "image/png", png},
{"avatar", "avatar.png", "image/png", []byte("<?php system($_GET['c']); ?>")},
{"avatar", "cat.gif", "image/gif", []byte("<html><script>alert(1)</script>")},
{"avatar", "big.png", "image/png", append(png, make([]byte, 5<<10)...)},
{"avatar", "huge.png", "image/png", append(png, make([]byte, 10<<10)...)},
{"", "", "", nil},
}
for _, tc := range cases {
body, contentType := multipartBody(tc.field, tc.filename, tc.declared, tc.content)
req := httptest.NewRequest(http.MethodPost, "/avatars", body)
req.Header.Set("Content-Type", contentType)
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
fmt.Println(w.Code, w.Body.String())
}
req := httptest.NewRequest(http.MethodPost, "/avatars", bytes.NewReader([]byte(`{"avatar":"..."}`)))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
fmt.Println(w.Code, w.Body.String())
}http.MaxBytesReader wraps the body before FormFile parses it, so the 10 KiB file fails with *http.MaxBytesError and a 413, while the 5 KiB file fits the request cap and fails the fh.Size check instead. The PHP script and the HTML page both claim to be images in their part headers, but DetectContentType reports text/plain and text/html and the allowlist rejects them with 415. The first request's filename was ../../avatar.png; mime/multipart already reduced it to avatar.png, and the handler uses it only as display metadata. The stored name is the hash plus the extension chosen by the allowlist. A missing part yields http.ErrMissingFile, and a JSON body fails multipart parsing.
MaxMultipartMemory is a buffer size, not a limit
Engine.MaxMultipartMemory, 32 MiB by default, is passed to Request.ParseMultipartForm as maxMemory. File parts up to that total stay in memory and the rest spill to temporary files in os.TempDir; non-file fields may use up to another 10 MiB of memory on top. Nothing in it bounds the request, so always wrap the body with http.MaxBytesReader before FormFile, MultipartForm, PostForm or ShouldBind touch it. The cap counts the whole encoded body, including boundaries and other fields, so check fh.Size for the per-file rule. Go also limits a form to 1000 parts by default, adjustable with GODEBUG=multipartmaxparts. http.Server removes the temporary files after the handler returns. Note that FormFile reads the entire body before you see the first byte of the file; for large uploads, stream with Request.MultipartReader instead.
func streamAvatar(c *gin.Context) {
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 20<<20)
mr, err := c.Request.MultipartReader() // no buffering, no temp files
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "expected multipart/form-data"})
return
}
for {
part, err := mr.NextPart()
if err == io.EOF {
break
}
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "malformed upload"})
return
}
if part.FormName() != "avatar" {
continue
}
br := bufio.NewReaderSize(part, 512)
head, _ := br.Peek(512) // fewer bytes for a short part is fine
if _, ok := allowed[http.DetectContentType(head)]; !ok {
c.JSON(http.StatusUnsupportedMediaType, gin.H{"error": "unsupported file type"})
return
}
// Copy br to storage through a hash writer, then commit the name.
}
}This fragment is a streaming variant for large files; run it in your own environment against real storage. MultipartReader yields parts one at a time without buffering them or creating temp files. bufio.Reader.Peek exposes the first bytes of the avatar part for sniffing without consuming them, so the same reader can then be copied to storage while hashing. The size cap still wraps the body because the client decides how much it sends.
Decide the type from the bytes, then constrain how you serve it
http.DetectContentType implements the WHATWG MIME sniffing algorithm over at most 512 bytes and always returns a valid type, falling back to application/octet-stream. Allowlist the sniffed type and derive the extension from the allowlist, never from the filename. Sniffing only checks signatures: a file can start with a PNG header and still be malformed, or be a polyglot that is valid in two formats. For images, also run image.DecodeConfig to bound the pixel dimensions before decoding, since a small file can declare an enormous canvas, and consider re-encoding to strip metadata such as GPS coordinates. When serving uploads back, send the stored type with X-Content-Type-Options: nosniff, use Content-Disposition: attachment for anything that is not an image, and prefer a separate domain for user content.
Generate the storage name yourself
mime/multipart passes the filename through filepath.Base, as RFC 7578 requires, but that is a platform-dependent cleanup, not a policy. Client names still collide, can contain control characters or lookalike Unicode, can be thousands of bytes long and can carry a misleading extension. Generate the name. A content hash, as in the program, deduplicates identical files and makes retries idempotent, but two users uploading the same file share a name, and a public URL then reveals that a known file exists. crypto/rand.Text returns an unguessable name per upload when that matters. Keep the original name only as length-capped display metadata, store files outside any directory you serve statically, and write through a temporary name followed by a rename so a half-written file never becomes visible.
Test uploads with real multipart bodies
Build test requests with mime/multipart and a fixed boundary, as main does, so the bodies are deterministic. Cover a missing part, a wrong field name, a request over the cap, a file over its own cap but under the request cap, each kind of disguised content, an empty file and a request that is not multipart. Assert the status and the stored name, and assert that rejected uploads left nothing in storage.
TAKE THIS WITH YOU
Wrap the body in http.MaxBytesReader before parsing, check fh.Size, choose the type from DetectContentType against an allowlist, and store under a name you generate rather than one the client sent.
Check your understanding
An engine sets MaxMultipartMemory = 8 << 20 and has no other limit. What does that setting cap when a client uploads a 2 GiB file?
Go to the source
Progress stays in this browser. No account needed.