45 lines
1.0 KiB
Go
45 lines
1.0 KiB
Go
|
package validator
|
|||
|
|
|||
|
import (
|
|||
|
"errors"
|
|||
|
"github.com/go-playground/locales/zh"
|
|||
|
ut "github.com/go-playground/universal-translator"
|
|||
|
"github.com/go-playground/validator/v10"
|
|||
|
zhTranslations "github.com/go-playground/validator/v10/translations/zh"
|
|||
|
"reflect"
|
|||
|
)
|
|||
|
|
|||
|
var zhLocales = zh.New()
|
|||
|
var validate = validator.New()
|
|||
|
var uni = ut.New(zhLocales)
|
|||
|
var trans, _ = uni.GetTranslator("zh")
|
|||
|
|
|||
|
// 验证器注册翻译器
|
|||
|
var _ = zhTranslations.RegisterDefaultTranslations(validate, trans)
|
|||
|
|
|||
|
func init() {
|
|||
|
//注册一个函数,获取struct tag里自定义的label作为字段名
|
|||
|
validate.RegisterTagNameFunc(func(fld reflect.StructField) string {
|
|||
|
if label := fld.Tag.Get("label"); len(label) > 0 {
|
|||
|
return label
|
|||
|
}
|
|||
|
|
|||
|
if jsonField := fld.Tag.Get("json"); len(jsonField) > 0 {
|
|||
|
return jsonField
|
|||
|
}
|
|||
|
|
|||
|
return fld.Name
|
|||
|
})
|
|||
|
}
|
|||
|
|
|||
|
func ValidateStruct(data interface{}) (err error) {
|
|||
|
err = validate.Struct(data)
|
|||
|
if err != nil {
|
|||
|
for _, e := range err.(validator.ValidationErrors) {
|
|||
|
err = errors.New(e.Translate(trans))
|
|||
|
break
|
|||
|
}
|
|||
|
}
|
|||
|
return
|
|||
|
}
|