From e41085a653ee1084b4c796726b206930b66b17ba Mon Sep 17 00:00:00 2001 From: Kubudak90 Date: Mon, 6 Apr 2026 01:08:50 +0300 Subject: [PATCH] fix: prevent superfluous response.WriteHeader call in EncodeJSONResponse The EncodeJSONResponse function was calling w.WriteHeader(status) before encoding the JSON response. If json.NewEncoder(w).Encode(i) failed, it would call http.Error() which internally calls WriteHeader again, causing the "http: superfluous response.WriteHeader call" error. This fix: 1. Encodes the JSON to a buffer first 2. Only writes the header if encoding succeeds 3. Uses http.Error() only on encoding failure (before any header is written) Fixes #407 --- server/routers.go | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/server/routers.go b/server/routers.go index 559950fec..8d7798d37 100644 --- a/server/routers.go +++ b/server/routers.go @@ -17,6 +17,7 @@ package server import ( + "bytes" "encoding/json" "net/http" @@ -79,10 +80,14 @@ func NewRouter(routers ...Router) http.Handler { // EncodeJSONResponse uses the json encoder to write an interface to the http response with an // optional status code func EncodeJSONResponse(i interface{}, status int, w http.ResponseWriter) { - w.Header().Set("Content-Type", "application/json; charset=UTF-8") - w.WriteHeader(status) - - if err := json.NewEncoder(w).Encode(i); err != nil { + // Encode to buffer first to avoid superfluous WriteHeader call on error + var buf bytes.Buffer + if err := json.NewEncoder(&buf).Encode(i); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) + return } + + w.Header().Set("Content-Type", "application/json; charset=UTF-8") + w.WriteHeader(status) + w.Write(buf.Bytes()) }