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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Validate size and type before touching disk so bad requests fail cheaply and safely.
- 2Generate server-side filenames instead of trusting client input to avoid collisions and path abuse.
- 3Map each failure mode to a precise HTTP status code so clients can react correctly.
Related explainers
go
package middleware import ( "net/http"
Per-IP write rate limiting in Gin
rate-limiting
middleware
concurrency
Intermediate
8 steps
javascript
import { useCallback, useRef, useState } from 'react'; export function ColorPicker({ initialColor = '#3b82f6', onCommit }) { const [committed, setCommitted] = useState(initialColor);
A validated color picker in React
uncontrolled-inputs
refs
validation
Intermediate
7 steps
go
package middleware import ( "net/http"
A content-type guard middleware in Gin
middleware
closures
http
Intermediate
7 steps
typescript
import { Injectable } from '@angular/core'; import { HttpClient, HttpEventType, HttpRequest } from '@angular/common/http'; import { Observable } from 'rxjs'; import { map, distinctUntilChanged, scan } from 'rxjs/operators';
Tracking upload progress in Angular
rxjs
http-events
state-reduction
Intermediate
8 steps
go
package api import ( "errors"
Turning Gin validation errors into JSON
validation
error-handling
http-handlers
Intermediate
9 steps
go
package breaker import ( "errors"
How a circuit breaker works in Go
circuit-breaker
state-machine
concurrency
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/handling-secure-file-uploads-in-gin-explained-go-27d1/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.