Multiple calls to response.WriteHeader in Go

My Go server processes requests. First I make a call response.WriteHeader()

to set a status code for my response. After that, I start writing bytes into the response body. If the browser cancels the request while copying bytes, I get an error:

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

      

My code catches this error, then calls http.Error()

. It calls again response.WriteHeader()

.

This seems to be the problem, but I'm not sure. Can this be avoided? How can I avoid being called twice response.WriteHeader()

when an error occurs while writing to the response body?

Thank!

+3


source to share


1 answer


The call .WriteHeader()

causes a response to be sent to the client over the network. Once the answer is on its way, there is no way to go back. The only thing you can do is log a local error (for the server admin to know), or perhaps just fail.



The "Error ()" function is used to send the full HTTP response (error), so you can only use this to replace and not in addition to sending your own response.

+3


source







All Articles