From 71807f3414b8e142120461254acd7953365d8097 Mon Sep 17 00:00:00 2001 From: Moritz Poldrack Date: Wed, 21 Oct 2026 21:33:58 +0200 Subject: [PATCH] fix(render): Stream JSON instead of buffering the message Currently, not only the object but also the serialized representation is kept in memory in full. For small objects that is usually fine, but when exporting large data structures this makes the memory explode. This gets even worse when exporting it indented. The byte-output has changed since the Encoder.Encode functions add an extra new-line, the marshaled output outside of that remains the same. --- codec/json/api.go | 7 +++++++ gin_test.go | 2 +- logger_test.go | 2 +- middleware_test.go | 2 +- render/json.go | 14 ++++++++------ 5 files changed, 18 insertions(+), 9 deletions(-) diff --git a/codec/json/api.go b/codec/json/api.go index f2135683..0e5da69f 100644 --- a/codec/json/api.go +++ b/codec/json/api.go @@ -37,6 +37,13 @@ type Encoder interface { Encode(v any) error } +// EncoderIndent is an interface for json marshallers that support setting an +// indentation character. +type EncoderIndent interface { + Encoder + SetIndent(prefix, indent string) +} + // Decoder an interface reads and decodes JSON values from an input stream. type Decoder interface { // UseNumber causes the Decoder to unmarshal a number into an any as a diff --git a/gin_test.go b/gin_test.go index 71a817a7..51d25c4d 100644 --- a/gin_test.go +++ b/gin_test.go @@ -1064,7 +1064,7 @@ func TestCustomUnmarshalStruct(t *testing.T) { w := httptest.NewRecorder() route.ServeHTTP(w, req) assert.Equal(t, 200, w.Code) - assert.Equal(t, `"2000/01/01"`, w.Body.String()) + assert.Equal(t, "\"2000/01/01\"\n", w.Body.String()) } // Test the fix for https://github.com/gin-gonic/gin/issues/4002 diff --git a/logger_test.go b/logger_test.go index 395d97e6..e996fba4 100644 --- a/logger_test.go +++ b/logger_test.go @@ -397,7 +397,7 @@ func TestErrorLogger(t *testing.T) { w = PerformRequest(router, http.MethodGet, "/print") assert.Equal(t, http.StatusInternalServerError, w.Code) - assert.Equal(t, "hola!{\"error\":\"this is an error\"}", w.Body.String()) + assert.Equal(t, "hola!{\"error\":\"this is an error\"}\n", w.Body.String()) } func TestLoggerWithWriterSkippingPaths(t *testing.T) { diff --git a/middleware_test.go b/middleware_test.go index 8dc7c3b3..352881ab 100644 --- a/middleware_test.go +++ b/middleware_test.go @@ -249,5 +249,5 @@ func TestMiddlewareWrite(t *testing.T) { w := PerformRequest(router, http.MethodGet, "/") assert.Equal(t, http.StatusBadRequest, w.Code) - assert.Equal(t, strings.ReplaceAll("hola\nbar{\"foo\":\"bar\"}{\"foo\":\"bar\"}event:test\ndata:message\n\n", " ", ""), strings.ReplaceAll(w.Body.String(), " ", "")) + assert.Equal(t, strings.ReplaceAll("hola\nbar{\"foo\":\"bar\"}\n{\"foo\":\"bar\"}\nevent:test\ndata:message\n\n", " ", ""), strings.ReplaceAll(w.Body.String(), " ", "")) } diff --git a/render/json.go b/render/json.go index 2f98676c..6e2ac06a 100644 --- a/render/json.go +++ b/render/json.go @@ -66,17 +66,19 @@ func (r JSON) WriteContentType(w http.ResponseWriter) { // WriteJSON marshals the given interface object and writes it with custom ContentType. func WriteJSON(w http.ResponseWriter, obj any) error { writeContentType(w, jsonContentType) - jsonBytes, err := json.API.Marshal(obj) - if err != nil { - return err - } - _, err = w.Write(jsonBytes) - return err + return json.API.NewEncoder(w).Encode(obj) } // Render (IndentedJSON) marshals the given interface object and writes it with custom ContentType. func (r IndentedJSON) Render(w http.ResponseWriter) error { r.WriteContentType(w) + + enc := json.API.NewEncoder(w) + if indentEnc, ok := enc.(json.EncoderIndent); ok { + indentEnc.SetIndent("", " ") + return indentEnc.Encode(r.Data) + } + jsonBytes, err := json.API.MarshalIndent(r.Data, "", " ") if err != nil { return err