go gin custom verification

We have already mentioned in the previous article that you can specify restrictions such as the size of the json field when binding in gin, but the error is in English. Now we want to make it in Chinese so that it can be read by the front end. The demo is as follows

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")
}

Insert image description here

Guess you like

Origin blog.csdn.net/weixin_43632687/article/details/132555812