gin框架自定義驗證錯誤提示信息

在使用 gin 框架的過程中, 請求驗證的錯誤信息返回一直困擾著我, gin 的文檔中是這樣來返回錯誤信息的

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

而我們得到的錯誤提示大概就是這樣的

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

這樣的提示信息不是很友好, 在 validator 文檔中也說明了這個信息只是用在開發時進行調試用的. 那么我們怎么返回自定義的驗證提示呢. 參考 validator 文檔, 我是這樣來實現的.

首先定義綁定模型

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 "參數錯誤"
}

如何使用模型, 以登錄方法為例

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 進行轉換
        })
    }
}

這樣, 當驗證錯誤的時候, 我們就可以返回自己定義的錯誤提示信息了.

如果有幫到你, 請點個贊吧.

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容