Why the following code works as expected but the next one does not?
resp.WriteHeader(http.StatusBadRequest) _, _ = resp.Write(byte(`status code is 400`))
But if we change the order and write the body first and header later:
_, _ = resp.Write(byte(`status code is not 400!!`)) resp.WriteHeader(http.StatusBadRequest)
The header is set to
http.StatusOK in Response 2.
Why does the order matter?
// If WriteHeader has not yet been called, Write calls // WriteHeader(http.StatusOK) before writing the data.
// Changing the header map after a call to WriteHeader (or // Write) has no effect unless the modified headers are // trailers.
So be careful and always write the status first, body next.