diff --git a/context.go b/context.go index 582d00f2..6d39eae3 100644 --- a/context.go +++ b/context.go @@ -1121,6 +1121,11 @@ func bodyAllowedForStatus(status int) bool { // Status sets the HTTP response code. func (c *Context) Status(code int) { c.Writer.WriteHeader(code) + // No-body statuses never call Write(), so flush now. Matches Render + // and makes CreateTestContext / ResponseRecorder observe the code (#4071). + if !bodyAllowedForStatus(code) { + c.Writer.WriteHeaderNow() + } } // Header is an intelligent shortcut for c.Writer.Header().Set(key, value). diff --git a/context_test.go b/context_test.go index b82e04d5..861cd5a9 100644 --- a/context_test.go +++ b/context_test.go @@ -1158,6 +1158,30 @@ func (*TestRender) Render(http.ResponseWriter) error { func (*TestRender) WriteContentType(http.ResponseWriter) {} +func TestContextStatusFlushesNoBodyCodes(t *testing.T) { + for _, code := range []int{ + http.StatusContinue, // 100 + http.StatusNoContent, // 204 + http.StatusNotModified, // 304 + } { + w := httptest.NewRecorder() + c, _ := CreateTestContext(w) + c.Status(code) + assert.Equal(t, code, w.Code, "Status(%d) must flush to ResponseRecorder", code) + assert.Equal(t, code, c.Writer.Status()) + } +} + +func TestContextStatusBuffersBodyAllowedCodes(t *testing.T) { + w := httptest.NewRecorder() + c, _ := CreateTestContext(w) + c.Status(http.StatusCreated) // 201 allows body + assert.Equal(t, http.StatusOK, w.Code, "body-allowed Status must not flush early") + assert.Equal(t, http.StatusCreated, c.Writer.Status()) + c.Writer.WriteHeaderNow() + assert.Equal(t, http.StatusCreated, w.Code) +} + func TestContextRenderIfErr(t *testing.T) { w := httptest.NewRecorder() c, _ := CreateTestContext(w)