feat(context): warn on multiple response writes

Adds a debug-mode warning in Context.Render() when the response body has
already been written. This matches the existing warning pattern in
response_writer.go for duplicate header writes.

Fixes #4477
This commit is contained in:
vierblatt 2026-07-05 02:23:51 +08:00
parent 34dac209ff
commit a2a45467de
2 changed files with 17 additions and 0 deletions

View File

@ -1208,6 +1208,10 @@ func (c *Context) Render(code int, r render.Render) {
return
}
if c.Writer.Written() {
debugPrint("[WARNING] Response body has already been written. Wanted to override response.")
}
if err := r.Render(c.Writer); err != nil {
// Pushing error to c.Errors
_ = c.Error(err)

View File

@ -251,3 +251,16 @@ func TestMiddlewareWrite(t *testing.T) {
assert.Equal(t, http.StatusBadRequest, w.Code)
assert.Equal(t, strings.ReplaceAll("hola\n<map><foo>bar</foo></map>{\"foo\":\"bar\"}{\"foo\":\"bar\"}event:test\ndata:message\n\n", " ", ""), strings.ReplaceAll(w.Body.String(), " ", ""))
}
func TestMultipleResponseWritesWarning(t *testing.T) {
router := New()
router.GET("/", func(c *Context) {
c.String(http.StatusOK, "first\n")
c.String(http.StatusOK, "second\n")
})
w := PerformRequest(router, http.MethodGet, "/")
assert.Equal(t, http.StatusOK, w.Code)
assert.Equal(t, "first\nsecond\n", w.Body.String())
}