gin framework custom validation error message

In the process of using gin frame, an error message requesting verification return has been bothering me, gin document is to return an error message

    router.POST("/loginJSON", func(c *gin.Context) {
        var json Login
        if err := c.ShouldBindJSON(&json); err == nil {
            if json.User == "manu" && json.Password == "123" {
                c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})
            } else {
                c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})
            }
        } else {
            c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        }
    })

The error we got probably the case

{
    "message": "Key: 'LoginRequest.Mobile' Error:Field validation for 'Mobile' failed on the 'required' tag\nKey: 'LoginRequest.Code' Error:Field validation for 'Code' failed on the 'required' tag"
}

This message is not very friendly, the validator document also describes the use of this information is only used for debugging during development. So how do we return authentication prompt customize it. Reference document validator, I was so accomplished.

First define binding model

import (
    "gopkg.in/go-playground/validator.v8"
)

// 绑定模型
type LoginRequest struct {
    Mobile string   `form:"mobile" json:"mobile" binding:"required"`
    Code string `form:"code" json:"code" binding:"required"`
}

// 绑定模型获取验证错误的方法
func (r *LoginRequest) GetError (err validator.ValidationErrors) string {

    // 这里的 "LoginRequest.Mobile" 索引对应的是模型的名称和字段
    if val, exist := err["LoginRequest.Mobile"]; exist {
        if val.Field == "Mobile" {
            switch val.Tag{
                case "required":
                    return "请输入手机号码"
            }
        }
    }
    if val, exist := err["LoginRequest.Code"]; exist {
        if val.Field == "Code" {
            switch val.Tag{
                case "required":
                    return "请输入验证码"
            }
        }
    }
    return "参数错误"
}

How to use the model, an example to log method

import (
    "github.com/gin-gonic/gin"
    "net/http"
    "gopkg.in/go-playground/validator.v8"
)


func Login(c *gin.Context) {
    var loginRequest LoginRequest

    if err := c.ShouldBind(&loginRequest); err == nil { 
        // 参数接收正确, 进行登录操作

        c.JSON(http.StatusOK, loginRequest)
    }else{
        // 验证错误
        c.JSON(http.StatusUnprocessableEntity, gin.H{
            "message": loginRequest.GetError(err.(validator.ValidationErrors)), // 注意这里要将 err 进行转换
        })
    }
}

Thus, when a validation error, we can return an error message their own definition of the.

If you have help, please point a praise it.

Guess you like

Origin blog.csdn.net/weixin_34364135/article/details/90809493