go
50 lines · 9 steps
Turning Gin validation errors into JSON
A Gin handler binds and validates JSON input, then maps each validation failure to a friendly per-field message.
Explained by
highlit
1type CreateUserInput struct {
2 Name string `json:"name" binding:"required,min=2,max=64"`
3 Email string `json:"email" binding:"required,email"`
4 Password string `json:"password" binding:"required,min=8"`
5 Age int `json:"age" binding:"required,gte=18,lte=120"`
6}
7
8func validationMessage(fe validator.FieldError) string {
9 switch fe.Tag() {
10 case "required":
11 return "this field is required"
12 case "email":
13 return "must be a valid email address"
14 case "min":
15 return "must be at least " + fe.Param() + " characters"
16 case "max":
17 return "must be at most " + fe.Param() + " characters"
18 case "gte":
19 return "must be greater than or equal to " + fe.Param()
20 case "lte":
21 return "must be less than or equal to " + fe.Param()
22 default:
23 return "is invalid"
24 }
25}
26
27func CreateUser(c *gin.Context) {
28 var input CreateUserInput
29 if err := c.ShouldBindJSON(&input); err != nil {
30 var ve validator.ValidationErrors
31 if errors.As(err, &ve) {
32 fields := make(map[string]string, len(ve))
33 for _, fe := range ve {
34 fields[fe.Field()] = validationMessage(fe)
35 }
36 c.JSON(http.StatusUnprocessableEntity, gin.H{"errors": fields})
37 return
38 }
39 c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request payload"})
40 return
41 }
42
43 user, err := userService.Create(c.Request.Context(), input.Name, input.Email, input.Password, input.Age)
44 if err != nil {
45 c.JSON(http.StatusInternalServerError, gin.H{"error": "could not create user"})
46 return
47 }
48
49 c.JSON(http.StatusCreated, user)
50}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Struct tags let you declare validation rules once and have Gin enforce them at bind time.
- 2Type-asserting the bind error with errors.As distinguishes user validation failures from malformed payloads.
- 3Translating validator tags into human messages gives clients actionable, field-level feedback.
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/turning-gin-validation-errors-into-json-explained-go-d5ae/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.