package api import ( "encoding/json" "net/http" "net/http/httptest" "testing" ) func TestWriteErr_EmitsJSONEnvelope(t *testing.T) { w := httptest.NewRecorder() writeErr(w, http.StatusBadRequest, "bad_request", "field x required") if w.Code != http.StatusBadRequest { t.Errorf("status = %d, want 400", w.Code) } if got := w.Header().Get("Content-Type"); got != "application/json" { t.Errorf("content-type = %q, want application/json", got) } var body struct { Error struct { Code string `json:"code"` Message string `json:"message"` } `json:"error"` } if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil { t.Fatalf("decode: %v\nbody=%s", err, w.Body.String()) } if body.Error.Code != "bad_request" || body.Error.Message != "field x required" { t.Errorf("body = %+v", body) } }