Bug: 11.7.1 The httptest package: Handler writes body before setting status code (test passes incorrectly)

Author: sandinvCreated Mar 25, 2026Updated Jul 5, 2026
Labelserratum

Incorrect status code

The HTTP handler writes the response body before calling WriteHeader, which causes Go to implicitly send a 200 OK status code. As a result, the later call to WriteHeader(http.StatusCreated) has no effect.

Additionally, the current test asserts http.StatusOK, which matches the unintended behavior. This allows the test to pass even though the handler appears to intend returning 201 Created.

Current implementation:

func Handler(w http.ResponseWriter, r *http.Request) {
	w.Header().Add("X-API-VERSION", "1.0")
	b, _ := io.ReadAll(r.Body)
	_, _ = w.Write(append([]byte("hello "), b...))
	w.WriteHeader(http.StatusCreated)
}

Issue

  • w.Write(...) is called before w.WriteHeader(...)
  • This implicitly sets the response status to 200 OK
  • The subsequent WriteHeader(http.StatusCreated) is ignored

Test issue

if http.StatusOK != w.Result().StatusCode {
	t.FailNow()
}
  • The test expects 200 OK, which matches the incorrect behavior
  • This hides the bug in the handler

Expected behavior

The handler should return 201 Created, as implied by the use of http.StatusCreated.

Proposed fix:

On Handler:

func Handler(w http.ResponseWriter, r *http.Request) {
	w.Header().Add("X-API-VERSION", "1.0")
	w.WriteHeader(http.StatusCreated)

	b, _ := io.ReadAll(r.Body)
	_, _ = w.Write(append([]byte("hello "), b...))
}

On the test:

if http.StatusCreated != w.Result().StatusCode {
	t.Fatalf("expected status %d, got %d", http.StatusCreated, w.Result().StatusCode)
}