mirror of
https://github.com/gin-gonic/gin.git
synced 2026-06-06 03:08:11 +08:00
Merge ec2c83899541c81bdb2063673d1f368117679726 into d75fcd4c9ab260e5225de590f1f0f8c0e0e12d11
This commit is contained in:
commit
f7f91fa9b8
@ -1185,6 +1185,10 @@ func (c *Context) Render(code int, r render.Render) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if c.Writer.Written() {
|
||||||
|
debugPrint("[WARNING] Response body already written. Attempting to write again with status code %d", code)
|
||||||
|
}
|
||||||
|
|
||||||
if err := r.Render(c.Writer); err != nil {
|
if err := r.Render(c.Writer); err != nil {
|
||||||
// Pushing error to c.Errors
|
// Pushing error to c.Errors
|
||||||
_ = c.Error(err)
|
_ = c.Error(err)
|
||||||
|
|||||||
@ -3868,3 +3868,47 @@ func BenchmarkGetMapFromFormData(b *testing.B) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestRenderMultipleWritesWarning(t *testing.T) {
|
||||||
|
// Test that a warning is printed when attempting to write response body multiple times
|
||||||
|
var w *httptest.ResponseRecorder
|
||||||
|
re := captureOutput(t, func() {
|
||||||
|
SetMode(DebugMode)
|
||||||
|
router := New()
|
||||||
|
router.GET("/test", func(c *Context) {
|
||||||
|
c.JSON(http.StatusOK, H{"first": "response"})
|
||||||
|
c.JSON(http.StatusOK, H{"second": "response"}) // Should trigger warning
|
||||||
|
})
|
||||||
|
w = httptest.NewRecorder()
|
||||||
|
req := httptest.NewRequest(http.MethodGet, "/test", nil)
|
||||||
|
router.ServeHTTP(w, req)
|
||||||
|
SetMode(TestMode)
|
||||||
|
})
|
||||||
|
|
||||||
|
// Should contain the warning about multiple writes
|
||||||
|
assert.Contains(t, re, "[WARNING] Response body already written")
|
||||||
|
assert.Contains(t, re, "200")
|
||||||
|
|
||||||
|
// Verify the response body contains both responses (behavior unchanged)
|
||||||
|
assert.Contains(t, w.Body.String(), "first")
|
||||||
|
assert.Contains(t, w.Body.String(), "second")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRenderMultipleWritesNoWarningInReleaseMode(t *testing.T) {
|
||||||
|
// Test that no warning is printed in release mode
|
||||||
|
re := captureOutput(t, func() {
|
||||||
|
SetMode(ReleaseMode)
|
||||||
|
router := New()
|
||||||
|
router.GET("/test", func(c *Context) {
|
||||||
|
c.JSON(http.StatusOK, H{"first": "response"})
|
||||||
|
c.JSON(http.StatusOK, H{"second": "response"})
|
||||||
|
})
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
req := httptest.NewRequest(http.MethodGet, "/test", nil)
|
||||||
|
router.ServeHTTP(w, req)
|
||||||
|
SetMode(TestMode)
|
||||||
|
})
|
||||||
|
|
||||||
|
// Should not contain the warning in release mode
|
||||||
|
assert.NotContains(t, re, "[WARNING] Response body already written")
|
||||||
|
}
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user