warning header were already written wanted to override status code 400 with 200问题排查

  • 问题

在测试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了,再覆写就会失效。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值