Go中有多个response.WriteHeader调用 [英] Multiple response.WriteHeader calls in Go

查看:184
本文介绍了Go中有多个response.WriteHeader调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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



这似乎是一个问题,但我不确定。这可以避免吗?如何避免在写入响应主体时发生错误? $ b

>感谢!

解决方案

.WriteHeader()的调用开始发送通过网络对客户的回应。一旦反应结束,就没有办法回来了。你可以做的唯一事情就是在本地记录错误(让服务器管理员知道)或者可能只是失败而已。



'Error()'函数是用来发送一个完整的HTTP(错误)响应,所以你只能用它来代替发送你自己的响应,而不是它。


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!

解决方案

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.

这篇关于Go中有多个response.WriteHeader调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆