go
64 lines · 8 steps
Localized validation errors in Gin
A Gin middleware that catches validator failures and returns them translated to the client's preferred language.
Explained by
highlit
1package middleware
2
3import (
4 "net/http"
5
6 "github.com/gin-gonic/gin"
7 "github.com/go-playground/locales/en"
8 "github.com/go-playground/locales/es"
9 "github.com/go-playground/locales/fr"
10 ut "github.com/go-playground/universal-translator"
11 "github.com/go-playground/validator/v10"
12 en_trans "github.com/go-playground/validator/v10/translations/en"
13 es_trans "github.com/go-playground/validator/v10/translations/es"
14 fr_trans "github.com/go-playground/validator/v10/translations/fr"
15)
16
17func NewValidationErrorHandler(validate *validator.Validate) gin.HandlerFunc {
18 uni := ut.New(en.New(), es.New(), fr.New())
19
20 enT, _ := uni.GetTranslator("en")
21 esT, _ := uni.GetTranslator("es")
22 frT, _ := uni.GetTranslator("fr")
23
24 _ = en_trans.RegisterDefaultTranslations(validate, enT)
25 _ = es_trans.RegisterDefaultTranslations(validate, esT)
26 _ = fr_trans.RegisterDefaultTranslations(validate, frT)
27
28 return func(c *gin.Context) {
29 c.Next()
30
31 if len(c.Errors) == 0 {
32 return
33 }
34
35 last := c.Errors.Last().Err
36 verrs, ok := last.(validator.ValidationErrors)
37 if !ok {
38 return
39 }
40
41 trans, _ := uni.FindTranslator(parseAcceptLanguage(c.GetHeader("Accept-Language"))...)
42
43 fields := make(map[string]string, len(verrs))
44 for _, fe := range verrs {
45 fields[fe.Field()] = fe.Translate(trans)
46 }
47
48 c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{
49 "error": "validation_failed",
50 "fields": fields,
51 })
52 }
53}
54
55func parseAcceptLanguage(header string) []string {
56 var locales []string
57 for _, part := range strings.Split(header, ",") {
58 tag := strings.TrimSpace(strings.SplitN(part, ";", 2)[0])
59 if tag != "" {
60 locales = append(locales, tag)
61 }
62 }
63 return locales
64}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A single universal-translator instance can be built once at setup and reused across every request the middleware handles.
- 2Post-processing middleware runs its logic after c.Next(), letting it inspect errors handlers accumulated during the request.
- 3Honoring the Accept-Language header turns generic validation failures into responses each client can actually read.
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
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 steps
go
package api import ( "crypto/sha256"
ETag conditional requests in Gin
http-caching
etag
conditional-requests
Intermediate
6 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/localized-validation-errors-in-gin-explained-go-2488/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.