1 回答

TA貢獻1852條經驗 獲得超7個贊
Gin gonic 使用該包github.com/go-playground/validator/v10
執行綁定驗證。如果驗證失敗,則返回的錯誤為validator.ValidationErrors
.
這沒有明確提及,但在模型綁定和驗證中它指出:
Gin 使用 go-playground/validator/v10 進行驗證。在此處查看有關標簽使用的完整文檔。
該鏈接指向go-playground/validator/v10
文檔,您可以在其中找到段落Validation Functions Return Type error。
您可以使用標準errors
包來檢查錯誤是否是那個,打開它,然后訪問單個字段,即validator.FieldError
. 由此,您可以構建任何您想要的錯誤消息。
給定這樣的錯誤模型:
type ApiError struct {
Field string
Msg string
}
你可以這樣做:
var u User
err := c.BindQuery(&u);
if err != nil {
var ve validator.ValidationErrors
if errors.As(err, &ve) {
out := make([]ApiError, len(ve))
for i, fe := range ve {
out[i] = ApiError{fe.Field(), msgForTag(fe.Tag())}
}
c.JSON(http.StatusBadRequest, gin.H{"errors": out})
}
return
}
使用輔助函數為您的驗證規則輸出自定義錯誤消息:
func msgForTag(tag string) string {
switch tag {
case "required":
return "This field is required"
case "email":
return "Invalid email"
}
return ""
}
在我的測試中,這輸出:
{
"errors": [
{
"Field": "Number",
"Msg": "This field is required"
}
]
}
PS:要獲得帶有動態鍵的 json 輸出,您可以使用map[string]string固定結構模型來代替。
- 1 回答
- 0 關注
- 146 瀏覽
添加回答
舉報