我正在使用带有 Gin 的 Go 1.17,我想在将数据发送到我的数据库之前实现结构验证。我以Gin 文档中的示例为例。
在结构中,我们可以声明不同的标签来验证一个字段,如下所示:
type User struct {
FirstName string `json:"first_name" binding:"required"`
LastName string `json:"last_name" binding:"required"`
Age uint8 `json:"age" binding:"gte=0,lte=130"`
Email string `json:"email" binding:"required,email"`
FavouriteColor string `json:"favourite_color" binding:"iscolor"`
}
在处理程序中,我可以抓住这样的错误:
var u User
if err := c.ShouldBindWith(&u, binding.Query); err == nil {
c.JSON(http.StatusOK, gin.H{"message": "Good Job"})
} else {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
}
错误消息将是:
{
"error": "Key: 'User.FirstName' Error:Field validation for 'FirstName' failed on the 'required' tag\nKey: 'User.LastName' Error:Field validation for 'LastName' failed on the 'required' tag\nKey: 'User.Email' Error:Field validation for 'Email' failed on the 'required' tag\nKey: 'User.FavouriteColor' Error:Field validation for 'FavouriteColor' failed on the 'iscolor' tag"
}
错误消息太冗长了如何向用户返回更好的错误?我想对 json 响应进行建模,例如:
{
"errors": [
"first_name": "This field is required",
"last_name": "This field is required",
"age": "This field is required",
"email": "Invalid email"
]
}
慕姐4208626
相关分类