Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

feat(api): emit Content-Length header on JSON responses (#5021)

Multica Eveb6adf23f9127
diff --git a/server/cmd/server/health.go b/server/cmd/server/health.go
index 798dc50cb8..9999b538dc 100644
--- a/server/cmd/server/health.go
+++ b/server/cmd/server/health.go
@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"net/http"
+ "strconv"
"sync"
"sync/atomic"
"time"
@@ -163,7 +164,17 @@ func (h *serverHealth) computeReadiness(parent context.Context) (readinessRespon
}
func writeJSON(w http.ResponseWriter, status int, v any) {
+ // Buffer the payload so we can emit an accurate Content-Length; encoding
+ // straight into the ResponseWriter after WriteHeader would force chunked
+ // transfer encoding and drop the header.
+ body, err := json.Marshal(v)
+ if err != nil {
+ body = []byte(`{"error":"failed to encode response"}`)
+ status = http.StatusInternalServerError
+ }
+ body = append(body, '\n')
w.Header().Set("Content-Type", "application/json")
+ w.Header().Set("Content-Length", strconv.Itoa(len(body)))
w.WriteHeader(status)
- _ = json.NewEncoder(w).Encode(v)
+ _, _ = w.Write(body)
}
diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.go
index 33f857c1d6..7dca3a0536 100644
--- a/server/internal/handler/handler.go
+++ b/server/internal/handler/handler.go
@@ -9,6 +9,7 @@ import (
"log/slog"
"net/http"
"net/netip"
+ "strconv"
"time"
"github.com/go-chi/chi/v5"
@@ -262,9 +263,23 @@ func New(queries *db.Queries, txStarter txStarter, hub *realtime.Hub, bus *event
}
func writeJSON(w http.ResponseWriter, status int, v any) {
+ // Marshal the body up front so we can advertise an accurate Content-Length
+ // header. Streaming straight into the ResponseWriter after WriteHeader forces
+ // net/http into chunked transfer encoding, which omits Content-Length; buffering
+ // first lets clients (and proxies) see the exact body size.
+ body, err := json.Marshal(v)
+ if err != nil {
+ // Fall back to a minimal, self-describing error payload rather than leaving
+ // the client with a half-written response.
+ body = []byte(`{"error":"failed to encode response"}`)
+ status = http.StatusInternalServerError
+ }
+ // Match the trailing newline that json.Encoder.Encode historically appended.
+ body = append(body, '\n')
w.Header().Set("Content-Type", "application/json")
+ w.Header().Set("Content-Length", strconv.Itoa(len(body)))
w.WriteHeader(status)
- json.NewEncoder(w).Encode(v)
+ _, _ = w.Write(body)
}
// writeMeasuredJSON behaves like writeJSON but returns the encoded body size so
@@ -278,6 +293,7 @@ func writeMeasuredJSON(w http.ResponseWriter, status int, v any) (int, error) {
}
body = append(body, '\n')
w.Header().Set("Content-Type", "application/json")
+ w.Header().Set("Content-Length", strconv.Itoa(len(body)))
w.WriteHeader(status)
if _, err := w.Write(body); err != nil {
return len(body), err
diff --git a/server/internal/handler/handler_writejson_test.go b/server/internal/handler/handler_writejson_test.go
index 268485f983..625384a5c8 100644
--- a/server/internal/handler/handler_writejson_test.go
+++ b/server/internal/handler/handler_writejson_test.go
@@ -4,6 +4,7 @@ import (
"bytes"
"net/http"
"net/http/httptest"
+ "strconv"
"testing"
)
@@ -97,3 +98,58 @@ func TestWriteMeasuredJSONByteIdenticalToWriteJSON(t *testing.T) {
t.Fatalf("expected '<' to be HTML-escaped out of the body, got %q", rec.Body.String())
}
}
+
+// TestWriteJSONSetsContentLength verifies that the JSON response writers advertise
+// an accurate Content-Length header. Encoding straight into the ResponseWriter after
+// WriteHeader forces net/http into chunked transfer encoding (no Content-Length), so
+// both writeJSON and writeMeasuredJSON buffer the body first and set the header
+// explicitly. The value must equal the exact number of bytes written on the wire.
+func TestWriteJSONSetsContentLength(t *testing.T) {
+ cases := []struct {
+ name string
+ v any
+ }{
+ {"empty_map", map[string]any{}},
+ {"simple", map[string]string{"hello": "world"}},
+ {"html_escapable", map[string]any{"s": `a<b> & "c" <script>`}},
+ {"unicode", map[string]any{"s": "héllo 世界 🚀"}},
+ {"nested", map[string]any{"a": []any{1, "two", true, nil}}},
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ rec := httptest.NewRecorder()
+ writeJSON(rec, http.StatusOK, tc.v)
+
+ got := rec.Header().Get("Content-Length")
+ if got == "" {
+ t.Fatalf("writeJSON did not set Content-Length header")
+ }
+ cl, err := strconv.Atoi(got)
+ if err != nil {
+ t.Fatalf("Content-Length %q is not an integer: %v", got, err)
+ }
+ if cl != rec.Body.Len() {
+ t.Fatalf("Content-Length = %d, want %d (actual body length)", cl, rec.Body.Len())
+ }
+
+ // writeMeasuredJSON must set the same, accurate Content-Length.
+ recMeasured := httptest.NewRecorder()
+ n, err := writeMeasuredJSON(recMeasured, http.StatusOK, tc.v)
+ if err != nil {
+ t.Fatalf("writeMeasuredJSON returned error: %v", err)
+ }
+ gotMeasured := recMeasured.Header().Get("Content-Length")
+ clMeasured, err := strconv.Atoi(gotMeasured)
+ if err != nil {
+ t.Fatalf("writeMeasuredJSON Content-Length %q is not an integer: %v", gotMeasured, err)
+ }
+ if clMeasured != recMeasured.Body.Len() || clMeasured != n {
+ t.Fatalf("writeMeasuredJSON Content-Length = %d, body = %d, reported = %d; all must match", clMeasured, recMeasured.Body.Len(), n)
+ }
+ if got != gotMeasured {
+ t.Fatalf("Content-Length differs: writeJSON=%q writeMeasuredJSON=%q", got, gotMeasured)
+ }
+ })
+ }
+}