mirror of
https://github.com/gin-gonic/gin.git
synced 2026-11-23 11:33:37 +08:00
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
This commit is contained in:
parent
34dac209ff
commit
22739cdafe
@ -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).
|
||||
|
||||
@ -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)
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user