Compare commits

...

5 Commits

Author SHA1 Message Date
Raju Ahmed
834c448c3b
Merge efdb77ebbdfdf52d7a49c29b1375d78943394af1 into e3118cc378d263454098924ebbde7e8d1dd2e904 2026-01-25 09:57:25 +08:00
Bo-Yi Wu
efdb77ebbd
Merge branch 'master' into master 2026-01-02 10:17:53 +08:00
Raju Ahmed
4d32cf970e
Merge branch 'master' into master 2025-12-28 18:17:49 +06:00
Raju Ahmed
dc128b7291 test(context): add tests for multiple JSON and SSE writes in debug mode 2025-12-28 18:02:10 +06:00
Raju Ahmed
8eb015d2bc fix(context): added warning for multiple writes to response body
warning works only in debug mode
2025-12-28 18:02:10 +06:00
2 changed files with 46 additions and 0 deletions

View File

@ -1156,6 +1156,15 @@ func (c *Context) Render(code int, r render.Render) {
return
}
if c.Writer.Written() && IsDebugging() {
// Skip warning for SSE and streaming responses (status code -1)
if code != -1 {
if _, ok := r.(sse.Event); !ok {
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)

View File

@ -1395,6 +1395,43 @@ func TestContextRenderNoContentData(t *testing.T) {
assert.Equal(t, "text/csv", w.Header().Get("Content-Type"))
}
// Test multiple JSON writes in debug mode
func TestContextRenderMultipleJSON(t *testing.T) {
w := httptest.NewRecorder()
c, _ := CreateTestContext(w)
oldMode := os.Getenv("GIN_MODE")
defer os.Setenv("GIN_MODE", oldMode)
SetMode(DebugMode)
output := captureOutput(t, func() {
c.JSON(http.StatusOK, H{"foo": "bar"})
c.JSON(http.StatusOK, H{"baz": "qux"})
})
assert.Equal(t, http.StatusOK, w.Code)
assert.Contains(t, output, "[WARNING] Response body already written")
assert.Contains(t, output, "status code 200")
}
// Test multiple SSE writes in debug mode
func TestContextRenderMultipleSSE(t *testing.T) {
w := httptest.NewRecorder()
c, _ := CreateTestContext(w)
oldMode := os.Getenv("GIN_MODE")
defer os.Setenv("GIN_MODE", oldMode)
SetMode(DebugMode)
output := captureOutput(t, func() {
c.SSEvent("message", "test1")
c.SSEvent("message", "test2")
})
assert.Equal(t, http.StatusOK, w.Code)
assert.NotContains(t, output, "[WARNING] Response body already written")
}
func TestContextRenderSSE(t *testing.T) {
w := httptest.NewRecorder()
c, _ := CreateTestContext(w)