1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
| package main
import ( "log" "net/http" "reflect" "regexp" "strings"
"github.com/gin-gonic/gin" "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" chTranslations "github.com/go-playground/validator/v10/translations/zh" )
type User struct { Name string `json:"name"` Mobile string `json:"mobile" binding:"required,mobile"` }
func ValidateMobile(fl validator.FieldLevel) bool { mobile := fl.Field().String() ok, _ := regexp.MatchString(`^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$`, mobile) if ok { return true } return false }
var trans ut.Translator
func main() { r := gin.Default()
if v, ok := binding.Validator.Engine().(*validator.Validate); ok { v.RegisterTagNameFunc(func(field reflect.StructField) string { name := strings.SplitN(field.Tag.Get("json"), ",", 2)[0] if name == "-" { return "" } return name })
zhT := zh.New() uni := ut.New(zhT, zhT)
var found bool trans, found = uni.GetTranslator("zh") if !found { log.Fatalln("zh not found") } _ = chTranslations.RegisterDefaultTranslations(v, trans)
_ = v.RegisterValidation("mobile", ValidateMobile) _ = v.RegisterTranslation("mobile", trans, func(ut ut.Translator) error { return ut.Add("mobile", "{0} 非法的手机号", false) }, func(ut ut.Translator, fe validator.FieldError) string { t, _ := ut.T("mobile", fe.Field()) return t }) }
r.POST("", Login) r.Run(":8080") }
func Login(c *gin.Context) { var u User err := c.ShouldBind(&u) if err != nil { ValidatorError(c, err) return }
c.JSON(http.StatusOK, u) return }
func ValidatorError(c *gin.Context, err error) { errs, ok := err.(validator.ValidationErrors) if !ok { c.JSON(http.StatusOK, gin.H{ "message": err.Error(), }) } c.JSON(http.StatusOK, gin.H{ "error": removeTopStruct(errs.Translate(trans)), }) return }
func removeTopStruct(field map[string]string) map[string]string { resp := make(map[string]string, len(field)) for k, v := range field { ks := strings.Split(k, ".") resp[ks[len(ks)-1]] = v } return resp }
|