From fc23a46a1e8c873beef897da81e864d98ea83bf6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C4=B0smail=20Da=C5=9Fc=C4=B1?= Date: Sat, 17 Jan 2026 20:41:36 +0300 Subject: [PATCH] feat: add warning for multiple response body writes Add a debug warning when attempting to write to the response body multiple times. This helps developers identify subtle bugs where middleware or handlers inadvertently write responses multiple times, resulting in invalid output (e.g., concatenated JSON objects). This change: - Adds a warning in Context.Render() when Writer.Written() is true - Follows the existing pattern used for header write warnings - Only shows in debug mode via debugPrint() - Is non-breaking and backward compatible Fixes #4477 Co-Authored-By: Claude Opus 4.5 --- context.go | 4 ++++ debug_test.go | 17 +++++++++++++++++ 2 files changed, 21 insertions(+) diff --git a/context.go b/context.go index c42459ff..562ef95b 100644 --- a/context.go +++ b/context.go @@ -1133,6 +1133,10 @@ func (c *Context) Render(code int, r render.Render) { 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 { // Pushing error to c.Errors _ = c.Error(err) diff --git a/debug_test.go b/debug_test.go index dab02133..8ddc4410 100644 --- a/debug_test.go +++ b/debug_test.go @@ -11,6 +11,7 @@ import ( "io" "log" "net/http" + "net/http/httptest" "os" "strings" "sync" @@ -178,3 +179,19 @@ func TestGetMinVer(t *testing.T) { _, e = getMinVer("go1.1.1.1") require.Error(t, e) } + +func TestRenderWarnsOnMultipleWrites(t *testing.T) { + re := captureOutput(t, func() { + SetMode(DebugMode) + w := httptest.NewRecorder() + c, _ := CreateTestContext(w) + + // First write + c.JSON(http.StatusOK, H{"first": "response"}) + // Second write should trigger warning + c.JSON(http.StatusOK, H{"second": "response"}) + + SetMode(TestMode) + }) + assert.Contains(t, re, "[WARNING] Response body already written") +}