feat(api): wrap JSON responses in envelope

Add response envelope middleware to standardize JSON responses as
`{code,data,message}` with consistent business codes across endpoints.
Update Swagger annotations and tests to reflect the new response shape.

BREAKING CHANGE: API responses are now wrapped in a response envelope; clients must read payloads from `data` and handle `code`/`message` fields.
This commit is contained in:
zenfun
2026-01-10 00:15:08 +08:00
parent f400ffde95
commit 33838b1e2c
40 changed files with 771 additions and 371 deletions

View File

@@ -2,13 +2,13 @@ package api
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"testing"
"github.com/alicebob/miniredis/v2"
"github.com/ez-api/ez-api/internal/middleware"
"github.com/ez-api/ez-api/internal/model"
"github.com/ez-api/ez-api/internal/service"
"github.com/gin-gonic/gin"
@@ -53,6 +53,7 @@ func TestMaster_ListTokens_AndUpdateToken(t *testing.T) {
}
r := gin.New()
r.Use(middleware.ResponseEnvelope())
r.GET("/v1/tokens", withMaster(h.ListTokens))
r.PUT("/v1/tokens/:id", withMaster(h.UpdateToken))
@@ -63,9 +64,7 @@ func TestMaster_ListTokens_AndUpdateToken(t *testing.T) {
t.Fatalf("expected 200, got %d body=%s", rr.Code, rr.Body.String())
}
var list []TokenView
if err := json.Unmarshal(rr.Body.Bytes(), &list); err != nil {
t.Fatalf("unmarshal list: %v", err)
}
decodeEnvelope(t, rr, &list)
if len(list) != 1 || list[0].ID != k.ID {
t.Fatalf("unexpected list: %+v", list)
}
@@ -79,9 +78,7 @@ func TestMaster_ListTokens_AndUpdateToken(t *testing.T) {
t.Fatalf("expected 200, got %d body=%s", rr.Code, rr.Body.String())
}
var updated TokenView
if err := json.Unmarshal(rr.Body.Bytes(), &updated); err != nil {
t.Fatalf("unmarshal updated: %v", err)
}
decodeEnvelope(t, rr, &updated)
if updated.Status != "suspended" {
t.Fatalf("expected status suspended, got %+v", updated)
}