我们在web开发中,你的应用可能会在不同国家使用,所以需要将相关的错误提示根据本地语言进行相应的提示,也即是所谓的国际化。本文简单的介绍一下,在Gin中如何实现多语言的验证。我们借助validator.v10
以及相应的语言包。
集成关键点
- 导入需要转换语言包
- 公共包:
"github.com/go-playground/validator/v10"
- 需要转换的包,比如英文和中文
- 公共包:
en2 "github.com/go-playground/locales/en"
zh2 "github.com/go-playground/locales/zh"
ut "github.com/go-playground/universal-translator"
en_translations "github.com/go-playground/validator/v10/translations/en"
zh_translations "github.com/go-playground/validator/v10/translations/zh"
- 结构体定义不在是
binding
,而是validate
type Person struct {
Age int `form:"age" validate:"required,gt=10"`
Name string `form:"name" validate:"required"`
Address string `form:"address" validate:"required"`
}
- 构建语言转换器以及注册
tans, _ := uni.GetTranslator(local)
tans, _ := uni.GetTranslator(local)
switch local {
case "en":
en_translations.RegisterDefaultTranslations(validate, tans)
case "zh":
zh_translations.RegisterDefaultTranslations(validate, tans)
default:
en_translations.RegisterDefaultTranslations(validate, tans)
}
-
校验以及获取错误信息
校验,调用
err := validate.Struct(xx)
;如果对返回的错误信息进行处理,validator返回的绑定错误信息格式:key = namespace & value = translated error
;我们可以一次性获取所有的转换信息或者每次一次,具体如下:
err := validate.Struct(person)
if err != nil {
errs := err.(validator.ValidationErrors)
// 一次性转换所有与的错误信息方式
fmt.Println(errs.Translate(trans))
// 每次转换一次
for _, e := range errs {
fmt.Println(e.Translate(trans))
}
}
具体示例
package main
import (
"github.com/gin-gonic/gin"
en2 "github.com/go-playground/locales/en"
zh2 "github.com/go-playground/locales/zh"
ut "github.com/go-playground/universal-translator"
"github.com/go-playground/validator/v10"
en_translations "github.com/go-playground/validator/v10/translations/en"
zh_translations "github.com/go-playground/validator/v10/translations/zh"
"log"
"net/http"
)
type Person struct {
Age int `form:"age" validate:"required,gt=10"`
Name string `form:"name" validate:"required"`
Address string `form:"address" validate:"required"`
}
// use a single instance , it caches struct info
var (
uni *ut.UniversalTranslator
validate *validator.Validate
)
func multiLangBindingHandler(c *gin.Context) {
local := c.DefaultQuery("local", "en")
log.Println("local:", local)
tans, _ := uni.GetTranslator(local)
switch local {
case "en":
en_translations.RegisterDefaultTranslations(validate, tans)
case "zh":
zh_translations.RegisterDefaultTranslations(validate, tans)
default:
en_translations.RegisterDefaultTranslations(validate, tans)
}
var person Person
if err := c.ShouldBind(&person); err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"message": err.Error(),
})
return
}
if err := validate.Struct(person); err != nil {
errs := err.(validator.ValidationErrors)
sliceErrs := []string{}
for _, e := range errs {
// can translate each error one at a time.
sliceErrs = append(sliceErrs, e.Translate(tans))
}
c.JSON(http.StatusBadRequest, gin.H{
// translate all error at once
// returns a map with key = namespace & value = translated error
// NOTICE: 2 errors are returned and you'll see something surprising
// translations are i18n aware!!!!
// eg. '10 characters' vs '1 character'
"message": errs.Translate(tans),
"sliceErrs": sliceErrs,
})
return
}
c.JSON(http.StatusOK, gin.H{
"personInfo": person,
})
}
func main() {
zh := zh2.New()
en := en2.New()
uni = ut.New(en, zh)
validate = validator.New()
router := gin.Default()
router.GET("/testMultiLangBinding", multiLangBindingHandler)
router.Run(":9999")
}
测试
测试案例 | 测试结果 |
---|---|
$ curl -X GET "localhost:9999/testMultiLangBinding" |
{"sliceErrs":["Age is a required field","Name is a required field","Address is a required field"]} |
$ curl -X GET "localhost:9999/testMultiLangBinding?local=zh&age=12&name=yunfeng&address=wuhan" |
{"personInfo":{"Age":12,"Name":"yunfeng","Address":"wuhan"}} |
$ curl -X GET "localhost:9999/testMultiLangBinding?local=zh&age=12&name=yunfeng&address=wuhan" |
{"personInfo":{"Age":12,"Name":"yunfeng","Address":"wuhan"}} |
$ curl -X GET "localhost:9999/testMultiLangBinding?local=zh" |
{"message":{"Person.Address":"Address为必填字段","Person.Age":"Age为必填字段","Person.Name":"Name为必填字段"},"sliceErrs":["Age为必填字段","Name为必填字段","Address为必填字段"]} |
参考资料
validator.v10
Translations & Custom Errors
有疑问加站长微信联系(非本文作者)