From 97d310b55ca24d9c0829aaff61ff646123f49442 Mon Sep 17 00:00:00 2001 From: chriswhelix Date: Tue, 15 Nov 2016 15:51:05 -0800 Subject: [PATCH] Honor normal gin write contract for context.JSON() Gin normally silently swallows errors writing to the client; however in WriteJSON (and thus context.JSON), the ResponseWriter was being passed directly into the JSON encoder, which will return an error if there's an error writing to the stream. For instance, context.JSON would panic with errors like "write tcp XXX-> YYY: write: connection reset by peer" if the client disconnected before the response was complete. This change makes JSON.Render() treat write errors the same as IndentedJSON, Data, and other renderers. --- render/json.go | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/render/json.go b/render/json.go index 32e6058d..b652c4c8 100644 --- a/render/json.go +++ b/render/json.go @@ -37,5 +37,10 @@ func (r IndentedJSON) Render(w http.ResponseWriter) error { func WriteJSON(w http.ResponseWriter, obj interface{}) error { writeContentType(w, jsonContentType) - return json.NewEncoder(w).Encode(obj) + jsonBytes, err := json.Marshal(obj) + if err != nil { + return err + } + w.Write(jsonBytes) + return nil }