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

Walkthrough

Space play step click any line
Three takeaways
  1. 1A single universal-translator instance can be built once at setup and reused across every request the middleware handles.
  2. 2Post-processing middleware runs its logic after c.Next(), letting it inspect errors handlers accumulated during the request.
  3. 3Honoring the Accept-Language header turns generic validation failures into responses each client can actually read.

Related explainers

Share this explainer

Here's the card — post it anywhere.

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