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 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?