douchuang4181
2014-11-16 20:34
浏览 231
已采纳

多个响应。Go中的WriteHeader调用

My Go server is handling requests I first make a call to response.WriteHeader() in order to set the status code for my response. After that I begin writing bytes into the response body. If the browser cancels the request while i'm copying the bytes, I get an error:

write tcp [::1]:52319: broken pipe

My code detects this error, then calls http.Error(). This calls response.WriteHeader() again.

This appears to be a problem, but I'm not sure. Can this be avoided? How do I avoid calling response.WriteHeader() again when an error occurs while writing to to the response body?

Thanks!

图片转代码服务由CSDN问答提供 功能建议

我的Go服务器正在处理我首先调用 response.WriteHeader()的请求 以便为我的回复设置状态代码。 之后,我开始将字节写入响应主体。 如果我在复制字节时浏览器取消了请求,则会收到错误消息:

 写入tcp [:: 1]:52319:管道破损
   
 
 

我的代码检测到此错误,然后调用 http.Error()。 这会再次调用 response.WriteHeader()

这似乎是一个问题,但我不确定。 可以避免吗? 当写入响应正文时发生错误时,如何避免再次调用 response.WriteHeader()

谢谢! < / DIV>

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duan33360 2015-04-22 07:47
    已采纳

    The call to .WriteHeader() starts sending the response to the client over the net. Once the response is on its way, there is no way to back. The only thing you can do is to log the error locally (to let the server administrator know) or maybe to just fail silently.

    The 'Error()' function is used to send a complete HTTP (error) response, so you can only use this to replace sending your own response, not in addition to it.

    打赏 评论

相关推荐 更多相似问题