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
go
func (h *ExportHandler) StreamExport(c *gin.Context) { datasetID := c.Param("id") ctx := c.Request.Context()
Streaming NDJSON progress with Gin
streaming
goroutines
channels
Advanced
8 steps
go
package handler type flightResult struct { status int
Deduping in-flight requests in Gin
middleware
concurrency
deduplication
Advanced
9 steps
javascript
const express = require('express'); const { createProxyMiddleware, fixRequestBody } = require('http-proxy-middleware'); const router = express.Router();
Building an API gateway proxy in Express
reverse-proxy
middleware
api-gateway
Intermediate
6 steps
rust
use axum::{ extract::{FromRequestParts, Query}, http::{request::Parts, StatusCode}, };
Building a custom Axum extractor for query filters
extractors
query-parsing
enums
Intermediate
8 steps
go
package middleware import ( "net/http"
Per-IP write rate limiting in Gin
rate-limiting
middleware
concurrency
Intermediate
8 steps
python
import asyncio from dataclasses import dataclass import aiohttp
Bounded-concurrency HTTP fetching with asyncio
async
concurrency
semaphore
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.