Gin框架-[WARNING] Headers were already written. Wanted to override status code 400 with 200

Gin框架编写PUT接口使用BindJSON绑定参数报错,当结构体绑定参数有误时, 状态码为400,强制返回200,结果code还是400.

原因 : BindXXX方法都return c.MustBindWith(obj, binding.XXX)。如果绑定错误,则c.AbortWithError(http.StatusBadRequest, err).SetType(ErrorTypeBind)。这将响应状态码设置为400,并将Content-Type标题设置为text/plain; charset=utf-8。如果强制修改成200,就会警告[WARNING] Headers were already written. Wanted to override status code 400 with 200。

解决方法 : 绑定结构体的方法把BindJSON改为ShouldBind。

posted @ 2021-02-08 11:01  hubb  阅读(2458)  评论(0编辑  收藏  举报