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 streaming import ( "bufio"
Streaming NDJSON logs over HTTP in Go
http-streaming
channels
select
Advanced
10 steps
php
<?php namespace App\Services\Checkout;
Validating coupons with Laravel's Pipeline
pipeline
chain of responsibility
transactions
Intermediate
7 steps
go
package api import ( "crypto/sha256"
ETag conditional requests in Gin
http-caching
etag
conditional-requests
Intermediate
6 steps
php
<?php namespace App\Services;
How a password strength validator works in PHP
validation
regular-expressions
data-driven
Intermediate
8 steps
go
func (w *Watcher) resetDebounce(d time.Duration) { if !w.timer.Stop() { select { case <-w.timer.C:
Debouncing a stream of events in Go
debounce
timers
channels
Advanced
7 steps
rust
use chrono::{Duration, NaiveDate}; #[derive(Debug)] pub struct DateRange {
Parsing and iterating date ranges in Rust
error-handling
iterators
parsing
Intermediate
7 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.