douou9786 2017-04-12 07:06
浏览 24
已采纳

如何在响应正文中分别设置错误代码和封送JSON?

In my application, when there is error I am writing a json error message on response body but this makes response code 200. I tried separately doing

json.NewEncoder(res).Encode(errorBody)
res.WriteHeader(http.StatusBadRequest)

But it still gives out response code 200 along with a warning that I am making multiple WriteHeader calls. I want to have something like

http.Error(res,"Some Error Message here",http.StatusBadRequest)

but instead of the error message in text format, I want it to be in JSON. What should I do?

  • 写回答

2条回答 默认 最新

  • dtmooir3395 2017-04-12 09:06
    关注

    You can write the header first and then the body.

    res.Header().Set("Content-Type", "application/json; charset=utf-8")
    res.WriteHeader(http.StatusBadRequest)
    if err = json.NewEncoder(res).Encode(err); err != nil {
        // handle encoder error
    }
    

    And if the response is still 200 and/or you're getting the warning, that means that you or some of the packages you use are writing the header for you in some other place.

    Update: (to answer relevant question from comment)

    json.NewEncoder(res).Encode(err) calls the Write method on res, and the implementation of Write from the standard net/http package automatically sets the status to 200 if it's not already set. And the implementation of WriteHeader checks whether status is already set or not and if it is, it just logs the warning and bails, without overwriting it.

    So if you wan't to control the status you need to call WriteHeader before your write to the response whether you're writing json with the encoder or calling res.Write yourself.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛