代码拉取完成,页面将自动刷新
package validator
import (
"reflect"
"strings"
"gitee.com/falling-ts/gower/services"
"github.com/gin-gonic/gin/binding"
"github.com/go-playground/locales/zh"
ut "github.com/go-playground/universal-translator"
"github.com/go-playground/validator/v10"
zhTrans "github.com/go-playground/validator/v10/translations/zh"
)
type Service struct {
*validator.Validate
ut.Translator
}
func New() services.ValidatorService {
return &Service{
Validate: binding.Validator.Engine().(*validator.Validate),
}
}
// Init 初始化
func (s *Service) Init(...services.Service) services.Service {
uni := ut.New(zh.New())
trans, _ := uni.GetTranslator("zh")
s.Translator = trans
if err := zhTrans.RegisterDefaultTranslations(s.Validate, trans); err != nil {
panic(err)
}
s.Validate.RegisterTagNameFunc(func(field reflect.StructField) string {
if name := field.Tag.Get("zh"); name != "" {
return name
}
return strings.ToLower(field.Name)
})
return s
}
// Translate 翻译错误
func (s *Service) Translate(errs validator.ValidationErrors) validator.ValidationErrorsTranslations {
trans := make(validator.ValidationErrorsTranslations)
var f validator.FieldError
for i := 0; i < len(errs); i++ {
f = errs[i].(validator.FieldError)
rawKey := f.StructField()
j := strings.LastIndex(rawKey, ".")
key := strings.ToLower(rawKey[j+1:])
trans[key] = f.Translate(s.Translator)
}
return trans
}
// GetTrans 获取翻译器
func (s *Service) GetTrans() ut.Translator {
return s.Translator
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。