Merge 22739cdafeb00e73d07da38bf0a57d3cc0036528 into 3b08cd7235bd5ad2f055aa9e38135f111f6c5926

This commit is contained in:
Ruben Pari 2026-09-19 16:13:49 -04:00 committed by GitHub
commit cb36cee611
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 29 additions and 0 deletions

View File

@ -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).

View File

@ -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)