如何解决Gin 绑定中间件总是失败
我正在尝试为杜松子酒验证自定义错误消息并遵循此线程中的建议:https://github.com/gin-gonic/gin/issues/430
我正在以这种方式尝试 gin 绑定中间件:
['checkIn','date','timestampAttribute' => 'checkIn'],['checkOut','timestampAttribute' => 'checkOut'],'compare','compareAttribute' => 'checkIn','operator' => '<','enableClientValidation' => false],
我使用 Postman 发送请求,虽然我发送了正确的请求,但它总是说: 键:“itemPostRequest.Name”错误:“必需”标签上的“名称”字段验证失败
如果我不使用绑定中间件:
package main
import (
"fmt"
"net/http"
"github.com/gin-gonic/gin"
)
type itemPostRequest struct {
Name string `json:"name" binding:"required"`
}
func main() {
router := gin.Default()
router.Use(func (c *gin.Context) {
c.Next()
fmt.Println(c.Errors)
})
router.POST("/item",gin.Bind(itemPostRequest{}),func (c *gin.Context) {
fmt.Println("Im inside handler")
req := c.MustGet(gin.BindKey).(*itemPostRequest)
fmt.Println(req)
c.JSON(http.StatusOK,gin.H{"success": true})
})
router.Run()
}
它有效,但我希望能够在进入处理程序之前绑定并返回错误,就像线程上的建议一样。为什么这不起作用?谢谢
解决方法
感谢评论,我意识到我错过了内容类型应用程序/json。我没有意识到这一点,因为我之前使用过 c.ShouldBindWithJSON 而它不需要这个标头。