- 问题
在测试gin框架时遇到了一个问题,在调用
c.JSON(http.StatusOK,...)
时warning
warning header were already written wanted to override status code 400 with 200
- 排查过程:
在handler里打点,查看在哪一个点出现了覆写问题。例如:
r.GET("/", func(c *gin.Context) {
fmt.Println("Handler: written =", c.Writer.Written())
c.JSON(200, gin.H{"message": "Hello"})
})
然后发现在代码中有一行的前后打点
fmt.Println("Handler: written =", c.Writer.Written())
c.BindJSON(&greq)
fmt.Println("Handler: written =", c.Writer.Written())
输出结果是
Handler: written = false
Handler: written = true
然后查golang接口手册
func (*Context) MustBindWith ¶
added in v1.3.0
func (c *Context) MustBindWith(obj any, b binding.Binding) error
MustBindWith binds the passed struct pointer using the specified binding engine. It will abort the request with HTTP 400 if any error occurs. See the binding package.
因此如果这一调用失败,已经写成400了,再覆写就会失效。