From 22739cdafeb00e73d07da38bf0a57d3cc0036528 Mon Sep 17 00:00:00 2001 From: RubenPari Date: Sat, 8 Aug 2026 09:56:43 +0200 Subject: [PATCH] fix(context): flush no-body status codes from Status No-body codes never call Write(), so CreateTestContext left ResponseRecorder at 200 after Status(204/304/1xx). Flush those now to match Render and AbortWithStatus. Fixes #4071 --- context.go | 5 +++++ context_test.go | 24 ++++++++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/context.go b/context.go index 1dc730e3..7d968433 100644 --- a/context.go +++ b/context.go @@ -1122,6 +1122,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 e8d305e4..2f7b3cd4 100644 --- a/context_test.go +++ b/context_test.go @@ -1134,6 +1134,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)