From cb3ac5a8381a8063edd94f21031ece9f46670aed Mon Sep 17 00:00:00 2001 From: Stephan Renatus Date: Fri, 11 Oct 2024 13:48:18 +0200 Subject: [PATCH] server/writer: don't call WriteStatus() twice on encoding errors Signed-off-by: Stephan Renatus --- server/writer/writer.go | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/server/writer/writer.go b/server/writer/writer.go index 378eb17efc..6135eac198 100644 --- a/server/writer/writer.go +++ b/server/writer/writer.go @@ -57,6 +57,9 @@ func Error(w http.ResponseWriter, status int, err *types.ErrorV1) { // JSON writes a response with the specified status code and object. The object // will be JSON serialized. +// Deprecated: This method is problematic when using a non-200 status `code`: if +// encoding the payload fails, it'll print "superfluous call to WriteHeader()" +// logs. func JSON(w http.ResponseWriter, code int, v interface{}, pretty bool) { enc := json.NewEncoder(w) if pretty { @@ -74,7 +77,18 @@ func JSON(w http.ResponseWriter, code int, v interface{}, pretty bool) { // JSONOK is a helper for status "200 OK" responses func JSONOK(w http.ResponseWriter, v interface{}, pretty bool) { - JSON(w, http.StatusOK, v, pretty) + enc := json.NewEncoder(w) + if pretty { + enc.SetIndent("", " ") + } + + w.Header().Add("Content-Type", "application/json") + // If Encode() calls w.Write() for the first time, it'll set the HTTP status + // to 200 OK. + if err := enc.Encode(v); err != nil { + ErrorAuto(w, err) + return + } } // Bytes writes a response with the specified status code and bytes.