package apiresponse import ( "encoding/json" "net/http" "net/http/httptest" "testing" ) func TestWriteError(t *testing.T) { req := httptest.NewRequest(http.MethodGet, "/test", nil) req = req.WithContext(WithTraceID(req.Context(), "trace-123")) rec := httptest.NewRecorder() WriteError(rec, req, http.StatusUnauthorized, CodeAuthInvalidToken, "invalid token", map[string]string{ "reason": "expired", }) if rec.Code != http.StatusUnauthorized { t.Fatalf("status = %d, want %d", rec.Code, http.StatusUnauthorized) } if ct := rec.Header().Get("Content-Type"); ct != "application/json; charset=utf-8" { t.Fatalf("content-type = %q", ct) } var body ErrorBody if err := json.NewDecoder(rec.Body).Decode(&body); err != nil { t.Fatalf("decode body: %v", err) } if body.Code != CodeAuthInvalidToken { t.Fatalf("code = %q", body.Code) } if body.Message != "invalid token" { t.Fatalf("message = %q", body.Message) } if body.TraceID != "trace-123" { t.Fatalf("trace_id = %q", body.TraceID) } details, ok := body.Details.(map[string]any) if !ok || details["reason"] != "expired" { t.Fatalf("details = %#v", body.Details) } }