go
40 lines · 8 steps
Structured validation errors in Gin
A Gin handler validates a nested JSON payload with binding tags and returns per-field errors when it fails.
Explained by
highlit
1package handler
2
3type LineItem struct {
4 SKU string `json:"sku" binding:"required,alphanum"`
5 Quantity int `json:"quantity" binding:"required,gt=0,lte=100"`
6 UnitCost float64 `json:"unit_cost" binding:"required,gt=0"`
7}
8
9type CreateOrderRequest struct {
10 CustomerID string `json:"customer_id" binding:"required,uuid"`
11 Currency string `json:"currency" binding:"required,iso4217"`
12 Items []LineItem `json:"items" binding:"required,min=1,max=50,dive"`
13}
14
15func CreateOrder(orders *OrderService) gin.HandlerFunc {
16 return func(c *gin.Context) {
17 var req CreateOrderRequest
18 if err := c.ShouldBindJSON(&req); err != nil {
19 var verrs validator.ValidationErrors
20 if errors.As(err, &verrs) {
21 fields := make(map[string]string, len(verrs))
22 for _, fe := range verrs {
23 fields[fe.Namespace()] = fe.Tag()
24 }
25 c.JSON(http.StatusUnprocessableEntity, gin.H{"errors": fields})
26 return
27 }
28 c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request body"})
29 return
30 }
31
32 order, err := orders.Create(c.Request.Context(), req.CustomerID, req.Currency, req.Items)
33 if err != nil {
34 c.JSON(http.StatusInternalServerError, gin.H{"error": "could not create order"})
35 return
36 }
37
38 c.JSON(http.StatusCreated, order)
39 }
40}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Struct tags let you declare validation rules declaratively instead of writing manual checks.
- 2Distinguishing validation errors from other bind failures gives clients actionable, field-level feedback.
- 3Returning a closure over a service keeps handlers testable and free of global state.
Related explainers
rust
use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
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
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/structured-validation-errors-in-gin-explained-go-67c1/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.