Why HTTP Status in Response is always StatusOK?

Why the following code works as expected but the next one does not?

Response 1

_, _ = resp.Write([]byte(`status code is 400`))

But if we change the order and write the body first and header later:

Response 2

_, _ = resp.Write([]byte(`status code is not 400!!`))

The header is set to http.StatusOK in Response 2.

Why does the order matter?

from .goenv/versions/1.14.0/src/net/http/server.go

    // 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.


Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: