go
50 lines · 7 steps
Struct-level validation for partial updates in Gin
A Gin handler enforces per-field formats and a cross-field 'at least one' rule using a custom struct-level validator.
Explained by
highlit
1package handlers
2
3import (
4 "net/http"
5
6 "github.com/gin-gonic/gin"
7 "github.com/go-playground/validator/v10"
8)
9
10type UpdateContactRequest struct {
11 Email string `json:"email" binding:"omitempty,email"`
12 Phone string `json:"phone" binding:"omitempty,e164"`
13 Handle string `json:"handle" binding:"omitempty,alphanum"`
14 DisplayName string `json:"display_name" binding:"omitempty,min=2,max=64"`
15}
16
17func validateContactPayload(sl validator.StructLevel) {
18 req := sl.Current().Interface().(UpdateContactRequest)
19
20 if req.Email == "" && req.Phone == "" && req.Handle == "" && req.DisplayName == "" {
21 sl.ReportError(req.Email, "email", "Email", "atleastone", "")
22 sl.ReportError(req.Phone, "phone", "Phone", "atleastone", "")
23 sl.ReportError(req.Handle, "handle", "Handle", "atleastone", "")
24 sl.ReportError(req.DisplayName, "display_name", "DisplayName", "atleastone", "")
25 }
26}
27
28func RegisterContactValidators(v *validator.Validate) {
29 v.RegisterStructValidation(validateContactPayload, UpdateContactRequest{})
30}
31
32func UpdateContact(c *gin.Context) {
33 var req UpdateContactRequest
34 if err := c.ShouldBindJSON(&req); err != nil {
35 c.JSON(http.StatusUnprocessableEntity, gin.H{
36 "error": "provide at least one of: email, phone, handle, display_name",
37 "details": err.Error(),
38 })
39 return
40 }
41
42 contactID := c.Param("id")
43 updated, err := contactService.ApplyPartialUpdate(c.Request.Context(), contactID, req)
44 if err != nil {
45 c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to update contact"})
46 return
47 }
48
49 c.JSON(http.StatusOK, updated)
50}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Field-level binding tags handle format checks while struct-level validators express rules that span multiple fields.
- 2Using omitempty on every field makes a payload valid when empty, so a cross-field rule is needed to require at least one value.
- 3Registering a validator once at startup lets Gin apply it automatically during ShouldBindJSON.
Related explainers
go
package theme import ( "fmt"
Per-tenant HTML templates with Gin's renderer
multi-tenancy
concurrency
html-templates
Advanced
8 steps
php
<?php namespace App\Http\Controllers;
Streaming a filtered CSV export in Laravel
streaming
csv-export
query-builder
Intermediate
9 steps
go
package auth import ( "net/http"
Setting and reading secure session cookies in Go
cookies
session-management
security
Intermediate
6 steps
go
package middleware import ( "net/http"
A maintenance-mode gate in Gin
middleware
atomic-flag
concurrency
Intermediate
8 steps
go
func ServeVideo(c *gin.Context) { id := c.Param("id") video, err := videoRepo.FindByID(c.Request.Context(), id) if err != nil {
Streaming video files with Gin
http streaming
range requests
file serving
Intermediate
6 steps
go
package handler type LineItem struct { SKU string `json:"sku" binding:"required,alphanum"`
Structured validation errors in Gin
validation
json-binding
error-handling
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/struct-level-validation-for-partial-updates-in-gin-explained-go-adab/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.