2022-01-13 02:23:00 +08:00
|
|
|
package user
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"github.com/go-playground/locales/zh_Hans_CN"
|
|
|
|
ut "github.com/go-playground/universal-translator"
|
|
|
|
"github.com/go-playground/validator/v10"
|
|
|
|
zh_translations "github.com/go-playground/validator/v10/translations/zh"
|
|
|
|
"github.com/gofiber/fiber/v2"
|
|
|
|
"reflect"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
|
|
|
var Validate *validator.Validate
|
|
|
|
var trans ut.Translator
|
|
|
|
|
|
|
|
func init() {
|
|
|
|
Validate = validator.New()
|
|
|
|
zh := zh_Hans_CN.New()
|
|
|
|
uni := ut.New(zh, zh)
|
|
|
|
var ok bool
|
|
|
|
trans, ok = uni.GetTranslator("zh_Hans_CN")
|
|
|
|
if !ok {
|
|
|
|
panic(fmt.Errorf("uni.GetTranslator(%s) failed", "zh"))
|
|
|
|
}
|
|
|
|
Validate.RegisterTagNameFunc(func(field reflect.StructField) string {
|
2022-01-13 02:33:44 +08:00
|
|
|
addWarp := func(tag string) string {
|
|
|
|
return "[" + tag + "]"
|
2022-01-13 02:23:00 +08:00
|
|
|
}
|
2022-01-13 02:33:44 +08:00
|
|
|
if labelTag := field.Tag.Get("label"); labelTag != "" {
|
|
|
|
return addWarp(labelTag)
|
|
|
|
}
|
|
|
|
if jsonTag := field.Tag.Get("json"); jsonTag != "" {
|
|
|
|
return addWarp(jsonTag)
|
|
|
|
}
|
|
|
|
return addWarp(field.Name)
|
2022-01-13 02:23:00 +08:00
|
|
|
})
|
|
|
|
err := zh_translations.RegisterDefaultTranslations(Validate, trans)
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func Bind(c *fiber.Ctx, out interface{}) error {
|
|
|
|
if reflect.TypeOf(out).Kind() != reflect.Ptr {
|
|
|
|
return NewError("bind must ptr")
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := c.BodyParser(out); err != nil {
|
|
|
|
return WarpError(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
err := Validate.Struct(out)
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
if errs, ok := err.(validator.ValidationErrors); ok {
|
|
|
|
errString := make([]string, 0, len(errs))
|
|
|
|
for _, fieldError := range errs.Translate(trans) {
|
|
|
|
errString = append(errString, fieldError)
|
|
|
|
}
|
|
|
|
err = fmt.Errorf("%s", strings.Join(errString, ","))
|
|
|
|
}
|
|
|
|
return WarpErrorWithCode(fiber.StatusBadRequest, err)
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|