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 server import ( "net/http"
Serving a single-page app with Gin
static-files
spa
routing
Intermediate
7 steps
go
package handlers import ( "fmt"
Handling multipart profile uploads in Gin
form binding
file upload
validation
Intermediate
7 steps
rust
use axum::{ extract::{Path, State}, http::StatusCode, response::{IntoResponse, Response},
Typed error handling in an Axum handler
error-handling
extractors
validation
Intermediate
9 steps
go
package metrics import ( "sync/atomic"
A lock-free request counter in Go
concurrency
atomics
lock-free
Intermediate
6 steps
typescript
import { Module, Injectable } from '@nestjs/common'; import { ConfigModule, ConfigService } from '@nestjs/config'; import * as Joi from 'joi';
Validated, typed config in NestJS
configuration
validation
dependency-injection
Intermediate
6 steps
java
public record ServerConfig(String host, int port, boolean tls, List<String> allowedOrigins) { public ServerConfig { Objects.requireNonNull(host, "host is required");
Validating config with a Java record
records
validation
immutability
Intermediate
9 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.