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.
This commit is contained in:
chriswhelix 2016-11-15 15:51:05 -08:00 committed by Bo-Yi Wu
parent 2cab17ba50
commit 97d310b55c
1 changed files with 6 additions and 1 deletions

View File

@ -37,5 +37,10 @@ func (r IndentedJSON) Render(w http.ResponseWriter) error {
func WriteJSON(w http.ResponseWriter, obj interface{}) error { func WriteJSON(w http.ResponseWriter, obj interface{}) error {
writeContentType(w, jsonContentType) writeContentType(w, jsonContentType)
return json.NewEncoder(w).Encode(obj) jsonBytes, err := json.Marshal(obj)
if err != nil {
return err
}
w.Write(jsonBytes)
return nil
} }