go
47 lines · 7 steps
Handling multipart profile uploads in Gin
A Gin handler binds a multipart form, validates and stores an uploaded avatar, then persists the profile.
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
13type ProfileForm struct {
14 Name string `form:"name" binding:"required"`
15 Bio string `form:"bio" binding:"max=500"`
16 Birthday time.Time `form:"birthday" time_format:"2006-01-02"`
17 Tags []string `form:"tags"`
18 Avatar *multipart.FileHeader `form:"avatar" binding:"required"`
19}
20
21func UpdateProfile(c *gin.Context) {
22 var form ProfileForm
23 if err := c.ShouldBind(&form); err != nil {
24 c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
25 return
26 }
27
28 if form.Avatar.Size > 5<<20 {
29 c.JSON(http.StatusRequestEntityTooLarge, gin.H{"error": "avatar exceeds 5MB"})
30 return
31 }
32
33 filename := fmt.Sprintf("%s%s", uuid.NewString(), filepath.Ext(form.Avatar.Filename))
34 dst := filepath.Join("uploads", "avatars", filename)
35 if err := c.SaveUploadedFile(form.Avatar, dst); err != nil {
36 c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to store avatar"})
37 return
38 }
39
40 userID := c.GetString("userID")
41 if err := profiles.Update(c, userID, form.Name, form.Bio, form.Birthday, form.Tags, dst); err != nil {
42 c.JSON(http.StatusInternalServerError, gin.H{"error": "could not update profile"})
43 return
44 }
45
46 c.JSON(http.StatusOK, gin.H{"name": form.Name, "avatar": dst})
47}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Struct tags let Gin bind and validate multipart fields declaratively before any handler logic runs.
- 2Generating a random filename with the original extension avoids collisions and path-injection from user input.
- 3Guarding each fallible step with an early JSON response keeps the happy path flat and readable.
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-multipart-profile-uploads-in-gin-explained-go-0504/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.