我们上一篇已经提到了gin中binding时候可以指定json字段大小等限制,但是那个错误却是英文的,现在想搞成中文的,以便前端可读,demo如下
package main
import (
"net/http"
"reflect"
"github.com/gin-gonic/gin"
"github.com/go-playground/validator/v10"
)
// binding 指明了json字段的限制,msg是自定义的错误提醒
type UserInfo struct {
UserName string `json:"username" binding:"required,min=4,max=6" msg:"username验证失败"`
Age int `json:"age" binding:"gt=18,lte=120" msg:"age验证失败"`
Password string `json:"password" binding:"required" msg:"密码校验失败"`
Password2 string `json:"password2" binding:"required,eqfield=Password" msg:"必填,切要与password一致"`
}
//any是泛型
func CoustomError(err error, obj any) map[string]string {
var errors map[string]string = make(map[string]string)
if err2, ok := err.(validator.ValidationErrors); ok {
// 反射
getObj := reflect.TypeOf(obj)
// 循环错误的验证
for _, v := range err2 {
if sf, exist := getObj.Elem().FieldByName(v.Field()); exist {
// 获取结构体中的msg属性
errors[v.Field()] = sf.Tag.Get("msg")
}
}
return errors
}
return nil
}
func validationcustomerror(c *gin.Context) {
var user UserInfo
err := c.ShouldBindJSON(&user)
if err != nil {
errors := CoustomError(err, &user)
c.JSON(http.StatusBadRequest, gin.H{"msg": errors})
} else {
c.JSON(http.StatusOK, gin.H{"msg": user})
return
}
}
func main() {
router := gin.Default()
router.POST("/validationcustomerror", validationcustomerror)
router.Run("localhost:8888")
}