mirror of
https://github.com/gin-gonic/gin.git
synced 2026-11-23 11:33:37 +08:00
Merge b821250200f22da0bba6d88c7323aa3ccd74c3fb into 3b08cd7235bd5ad2f055aa9e38135f111f6c5926
This commit is contained in:
commit
0c896f0c38
@ -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