2

My server behaves well though I find the exception of "http: multiple response.WriteHeader calls". This exception doesn't cause my server panic or behaving weirdly.

I have searched a lot but only found how to solve this problem. There's no doc describing the bad effects of the exception. Could someone help me find why "http: multiple response.WriteHeader calls" is an exception and what the bad effects are that it causes? Thanks in advance.

UPDATE

I have read the source code here:

enter image description here

When calling WriteHeader multitimes,it only prints a log and then does nothing. It seems that calling WriteHeader multitimes doesn't cause the server behaves weiredly.

flyer
  • 9,280
  • 11
  • 46
  • 62
  • 2
    Possible duplicate of [Multiple response.WriteHeader calls in Go](http://stackoverflow.com/questions/26961764/multiple-response-writeheader-calls-in-go) – Zoyd Mar 20 '17 at 14:42
  • @Zoyd My question is different from that. I want to know the bad effects of "http: multiple response.WriteHeader calls" while that one explains why that's impossible that call `WriteHeader` again after having called `WriteHeader`. – flyer Mar 20 '17 at 14:46
  • The answer shows that calling WriteHeader multiple times doesn’t make sense. Therefore, if it happens, it necessarily points to some kind of mistake or unintended behaviour. – Zoyd Mar 20 '17 at 14:49
  • Though it doesn't make sense, it's ok if it doesn't cause something behave weirdly. – flyer Mar 20 '17 at 14:51

2 Answers2

3

You can only write a response header once before it is sent to the client. Because your code is attempting to write a response header after it has been sent to the client, the client will never see the final response you are trying to send.

You either have a bug where the client is getting the incorrect response which you later revised, or you have a bug where you are executing the wrong code after the correct response header has been written. Either way it's a bug.

JimB
  • 104,193
  • 13
  • 262
  • 255
  • From [the source code](https://golang.org/src/net/http/server.go#L1052), the client won't get s second response header. – flyer Mar 21 '17 at 02:32
  • @flyer: of course, because you can't really respond more than once. The server is warning you about a problem with your code so you can correct it. – JimB Mar 21 '17 at 02:39
2

The bad effect is that the actual result will most probably be different from what you expect. If you call WriteHeader(200) on line 10, and later on line 50 you call, on the same ResponseWriter, WriteHeader(404) what do you expect the response code to be? 404, or 200?

WriteHeader ignores subsequent calls and tells you about it by logging that message, so that when you're getting 200 instead of 404 as you probably expect, you just take a look at the server logs and you know what's up. The message is there to help you.

mkopriva
  • 35,176
  • 4
  • 57
  • 71