英文:
Multiple response.WriteHeader calls in Go
问题
我的Go服务器正在处理请求。首先,我调用response.WriteHeader()
来设置响应的状态码。然后,我开始向响应体中写入字节。如果浏览器在我复制字节时取消了请求,我会收到一个错误信息:
write tcp [::1]:52319: broken pipe
我的代码会检测到这个错误,然后调用http.Error()
。这会再次调用response.WriteHeader()
。
这似乎是一个问题,但我不确定。有没有办法避免这种情况发生?当在向响应体写入数据时发生错误时,如何避免再次调用response.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!
答案1
得分: 4
调用.WriteHeader()
方法开始将响应发送给客户端。一旦响应开始发送,就无法回退。你唯一能做的就是在本地记录错误(以便通知服务器管理员)或者可能只是静默地失败。
Error()
函数用于发送完整的HTTP(错误)响应,因此你只能使用它来替换发送自己的响应,而不能与之同时使用。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论