feat: 添加认证、日志、响应等基础中间件与服务
This commit is contained in:
1 parent
16a9f64109
commit
329a22f0b1
30 files changed
+1835
-12
No files matched your search
@@ -0,0 +1,48 @@
|
||||
package validata
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"reflect"
|
||||
"strings"
|
||||
|
||||
"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"
|
||||
zhtranslations "github.com/go-playground/validator/v10/translations/zh"
|
||||
)
|
||||
|
||||
var trans ut.Translator
|
||||
|
||||
func init() {
|
||||
// 创建翻译器
|
||||
uni := ut.New(zh.New())
|
||||
trans, _ = uni.GetTranslator("zh")
|
||||
|
||||
// 注册翻译器
|
||||
v, ok := binding.Validator.Engine().(*validator.Validate)
|
||||
if ok {
|
||||
_ = zhtranslations.RegisterDefaultTranslations(v, trans)
|
||||
}
|
||||
v.RegisterTagNameFunc(func(field reflect.StructField) string {
|
||||
label := field.Tag.Get("label")
|
||||
if label == "" {
|
||||
return field.Name
|
||||
}
|
||||
return label
|
||||
})
|
||||
}
|
||||
|
||||
func ValidateErr(err error) string {
|
||||
var errs validator.ValidationErrors
|
||||
if !errors.As(err, &errs) {
|
||||
return err.Error()
|
||||
}
|
||||
|
||||
list := make([]string, 0, len(errs))
|
||||
for _, e := range errs {
|
||||
list = append(list, e.Translate(trans))
|
||||
}
|
||||
|
||||
return strings.Join(list, ";")
|
||||
}
|
||||
Reference in new issue
Block a user