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

Walkthrough

Space play step click any line
Three takeaways
  1. 1Field-level binding tags handle format checks while struct-level validators express rules that span multiple fields.
  2. 2Using omitempty on every field makes a payload valid when empty, so a cross-field rule is needed to require at least one value.
  3. 3Registering a validator once at startup lets Gin apply it automatically during ShouldBindJSON.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Struct-level validation for partial updates in Gin — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code