3

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!

Mixcels
  • 889
  • 1
  • 11
  • 23
Jordan
  • 1,599
  • 4
  • 26
  • 42
  • 8
    There is no point in trying to respond with an error if the client already disconnected. – Arjan Nov 16 '14 at 20:36
  • @Arjan - makes sense...What's the proper way to handle this scenario? – Jordan Nov 16 '14 at 20:37
  • 1
    http://stackoverflow.com/questions/11003692/filter-out-broken-pipe-errors – thwd Nov 16 '14 at 23:51
  • Cool, I learned something. +1 – weberc2 Nov 17 '14 at 05:42
  • 7
    In general, though, if you've already called `WriteHeader` you shouldn't call `Error`. You can't switch response status in HTTP, even if the client is still listening on the other side and some other error has suddenly happened. – Jason Coco Nov 17 '14 at 17:34
  • @JasonCoco How do you switch the response status? Couldn't find anything in the docs. – Jordan Nov 17 '14 at 18:56
  • 1
    @Jordan You can't switch it. Once you write the status to the HTTP stream, it can't be changed. It's the first thing that gets sent back to the client according to the protocol. – Jason Coco Nov 17 '14 at 20:45
  • As there doesn't seem to be anything left to answer, could you please answer & accept it... – user918176 Nov 28 '14 at 18:05

1 Answers1

4

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.

jochen
  • 3,728
  • 2
  • 39
  • 49