gin框架自定義驗(yàn)證錯(cuò)誤提示信息

在使用 gin 框架的過(guò)程中, 請(qǐng)求驗(yàn)證的錯(cuò)誤信息返回一直困擾著我, gin 的文檔中是這樣來(lái)返回錯(cuò)誤信息的

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

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

{
    "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 文檔中也說(shuō)明了這個(gè)信息只是用在開(kāi)發(fā)時(shí)進(jìn)行調(diào)試用的. 那么我們?cè)趺捶祷刈远x的驗(yàn)證提示呢. 參考 validator 文檔, 我是這樣來(lái)實(shí)現(xiàn)的.

首先定義綁定模型

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

// 綁定模型獲取驗(yàn)證錯(cuò)誤的方法
func (r *LoginRequest) GetError (err validator.ValidationErrors) string {

    // 這里的 "LoginRequest.Mobile" 索引對(duì)應(yīng)的是模型的名稱和字段
    if val, exist := err["LoginRequest.Mobile"]; exist {
        if val.Field == "Mobile" {
            switch val.Tag{
                case "required":
                    return "請(qǐng)輸入手機(jī)號(hào)碼"
            }
        }
    }
    if val, exist := err["LoginRequest.Code"]; exist {
        if val.Field == "Code" {
            switch val.Tag{
                case "required":
                    return "請(qǐng)輸入驗(yàn)證碼"
            }
        }
    }
    return "參數(shù)錯(cuò)誤"
}

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

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 { 
        // 參數(shù)接收正確, 進(jìn)行登錄操作

        c.JSON(http.StatusOK, loginRequest)
    }else{
        // 驗(yàn)證錯(cuò)誤
        c.JSON(http.StatusUnprocessableEntity, gin.H{
            "message": loginRequest.GetError(err.(validator.ValidationErrors)), // 注意這里要將 err 進(jìn)行轉(zhuǎn)換
        })
    }
}

這樣, 當(dāng)驗(yàn)證錯(cuò)誤的時(shí)候, 我們就可以返回自己定義的錯(cuò)誤提示信息了.

如果有幫到你, 請(qǐng)點(diǎn)個(gè)贊吧.

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容