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

Walkthrough

Space play step click any line
Three takeaways
  1. 1Struct tags let you declare validation rules once and have Gin enforce them at bind time.
  2. 2Type-asserting the bind error with errors.As distinguishes user validation failures from malformed payloads.
  3. 3Translating validator tags into human messages gives clients actionable, field-level feedback.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Turning Gin validation errors into JSON — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code