[GIN-debug] [WARNING] Headers were already written. Wanted to override status code 400 with 200
环境: Golang
框架: gin
发生条件: 返回
我简单封装了一个response方法
func (ac *ApiController) Response(ctx *gin.Context, httpCode, errCode int, data gin.H) {
msg := codemsg.GetMsgByCode(errCode)
if data == nil {
ctx.JSON(httpCode, gin.H{
"code": errCode,
"message": msg,
"data": struct{}{},
})
} else {
ctx.JSON(httpCode, gin.H{
"code": errCode,
"message": msg,
"data": data,
})
}
logger.GetLogger().Info(ctx, "method", "API Response", "code", errCode, "errMsg", msg)
ctx.Abort()
return
}
当我接受参数时
var param dto.StartParam
err := ctx.BindJson(¶m)
if err != nil {
logger.GetLogger().Error(ctx, "method", method, "err", err)
c.Response(ctx, http.StatusOK, codemsg.DecodeInformGetParamFail, nil)
return
}
然后报错了
trace_id=f5db2a1d-3754-4480-b630-e64e51cae0df method=[ReconciliationController.Start] err=EOF [GIN-debug] [WARNING] Headers were already written. Wanted to override status code 400 with 200
错误理由很简单,我response重写了请求头的响应码
但是我不想修改http的响应码
看下 BindJson源码就知道了
// BindJSON is a shortcut for c.MustBindWith(obj, binding.JSON).
func (c *Context) BindJSON(obj interface{}) error {
return c.MustBindWith(obj, binding.JSON)
}
MustBindWith 方法源码
// 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.
func (c *Context) MustBindWith(obj interface{}, b binding.Binding) error {
if err := c.ShouldBindWith(obj, b); err != nil {
c.AbortWithError(http.StatusBadRequest, err).SetType(ErrorTypeBind) // nolint: errcheck
return err
}
return nil
}
c.AbortWithError(http.StatusBadRequest, err).SetType(ErrorTypeBind) // nolint: errcheck
搁这呢!
已经设置了错误码,abort 是中断请求流程,这个是中断请求流程并设置错误码
BindJson –> ShouldBind
换个方法使用即可
本站(PHP --> Golang)已重构,代码开源
当你能力不能满足你的野心的时候,你就该沉下心来学习