【Golang】Gin 框架之请求参数多语言验证

云枫随笔 · · 2879 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

我们在web开发中,你的应用可能会在不同国家使用,所以需要将相关的错误提示根据本地语言进行相应的提示,也即是所谓的国际化。本文简单的介绍一下,在Gin中如何实现多语言的验证。我们借助validator.v10以及相应的语言包。

集成关键点

  1. 导入需要转换语言包
    • 公共包: "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"
  1. 结构体定义不在是 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"`
}
  1. 构建语言转换器以及注册
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)
    }
  1. 校验以及获取错误信息

    校验,调用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


有疑问加站长微信联系(非本文作者)

本文来自:简书

感谢作者:云枫随笔

查看原文:【Golang】Gin 框架之请求参数多语言验证

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

2879 次点击  ∙  1 赞  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传