go validator实现中文翻译
在使用go-kratos v2的过程中,官方对于参数验证推荐了[protoc-gen-validate] (https://github.com/envoyproxy/protoc-gen-validate),但是由于返回值是中文,就算了用了middleware去处理,也无法完全中文化。所以采用了validator.
示例代码如下
用户结构体, validate表示validator验证规则, label用于中文文案提示
建立validator/validator.go
package validator
import (
"errors"
"reflect"
)
import (
"github.com/go-playground/locales/zh"
ut "github.com/go-playground/universal-translator"
"github.com/go-playground/validator/v10"
zh_translations "github.com/go-playground/validator/v10/translations/zh"
)
const (
BadRequest = "请求参数错误"
)
// ValidateData 全局model数据验证器
func Validate(dataStruct interface{}) error {
//验证
zh_ch := zh.New()
validate := validator.New()
//注册一个函数,获取struct tag里自定义的label作为字段名
validate.RegisterTagNameFunc(func(fld reflect.StructField) string {
name := fld.Tag.Get("label")
return name
})
uni := ut.New(zh_ch)
trans, _ := uni.GetTranslator("zh")
//验证器注册翻译器
zh_translations.RegisterDefaultTranslations(validate, trans)
err := validate.Struct(dataStruct)
if err != nil {
for _, err := range err.(validator.ValidationErrors) {
return errors.New(err.Translate(trans))
}
}
return nil
}
main.go
type User struct {
Id int64 `validate:"required" label:"id" ignoreRequired:"true"`
Name string `validate:"required" label:"姓名"`
}
func main(){
var u User
u.Id = 0
u.Name = ""
if err := validator.Validate(user); err != nil {
fmt.Println(err.Error())
return
}
return
}