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.