multiple response.WriteHeader calls in really simple example?

Take a look at the anonymous function you register as the handler of incoming requests:

func(w http.ResponseWriter, r *http.Request) {
    fmt.Println(r.URL)
    go HandleIndex(w, r)
}

It prints the URL (to the standard output) then calls HandleIndex() in a new goroutine and continues execution.

If you have a handler function where you do not set the response status before the first call to Write, Go will automatically set the response status to 200 (HTTP OK). If the handler function does not write anything to the response (and does not set the response status and completes normally), that is also treated as a successful handling of the request and the response status 200 will be sent back. Your anonymous function does not set it, it does not even write anything to the response. So Go will do just that: set the response status to 200 HTTP OK.

Note that handling each request runs in its own goroutine.

So if you call HandleIndex in a new goroutine, your original anonymous function will continue: it will end and so the response header will be set – meanwhile (concurrently) your started new goroutine will also set the response header – hence the "multiple response.WriteHeader calls" error.

If you remove the "go", your HandleIndex function will set the response header in the same goroutine before your handler function returns, and the “net/http” will know about this and will not try to set the response header again, so the error you experienced will not happen.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)