go 53 lines · 7 steps

Handling secure file uploads in Gin

A Gin handler that validates, renames, and stores an uploaded file with layered safety checks.

Explained by highlit
1package handlers
2 
3import (
4 "fmt"
5 "net/http"
6 "path/filepath"
7 "time"
8 
9 "github.com/gin-gonic/gin"
10 "github.com/google/uuid"
11)
12 
13const maxUploadSize = 5 << 20
14 
15var allowedExtensions = map[string]bool{
16 ".jpg": true,
17 ".jpeg": true,
18 ".png": true,
19 ".pdf": true,
20}
21 
22func UploadDocument(c *gin.Context) {
23 file, err := c.FormFile("document")
24 if err != nil {
25 c.JSON(http.StatusBadRequest, gin.H{"error": "document file is required"})
26 return
27 }
28 
29 if file.Size > maxUploadSize {
30 c.JSON(http.StatusRequestEntityTooLarge, gin.H{"error": "file exceeds 5MB limit"})
31 return
32 }
33 
34 ext := filepath.Ext(file.Filename)
35 if !allowedExtensions[ext] {
36 c.JSON(http.StatusUnsupportedMediaType, gin.H{"error": "file type not allowed"})
37 return
38 }
39 
40 filename := fmt.Sprintf("%d-%s%s", time.Now().Unix(), uuid.NewString(), ext)
41 dst := filepath.Join("uploads", filename)
42 
43 if err := c.SaveUploadedFile(file, dst); err != nil {
44 c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to store file"})
45 return
46 }
47 
48 c.JSON(http.StatusCreated, gin.H{
49 "filename": filename,
50 "size": file.Size,
51 "url": "/files/" + filename,
52 })
53}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Validate size and type before touching disk so bad requests fail cheaply and safely.
  2. 2Generate server-side filenames instead of trusting client input to avoid collisions and path abuse.
  3. 3Map each failure mode to a precise HTTP status code so clients can react correctly.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Handling secure file uploads in Gin — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code