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 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/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.