API契约:统一首批错误与账号列表 DTO
This commit is contained in:
1 parent
9f99f2b78a
commit
4e7abf61be
16 files changed
+453
-75
No files matched your search
@@ -0,0 +1,89 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/go-chi/chi/v5/middleware"
|
||||
"xianyu-go/internal/httpapi"
|
||||
)
|
||||
|
||||
// healthResponse 是健康检查接口的具名响应 DTO。
|
||||
type healthResponse struct {
|
||||
// Status 表示服务总体健康状态。
|
||||
Status string `json:"status"`
|
||||
// Database 表示数据库连接状态。
|
||||
Database string `json:"database"`
|
||||
// Version 是当前构建版本。
|
||||
Version string `json:"version,omitempty"`
|
||||
// Commit 是当前构建对应的短提交标识。
|
||||
Commit string `json:"commit,omitempty"`
|
||||
// BuildTime 是构建时注入的时间信息。
|
||||
BuildTime string `json:"build_time,omitempty"`
|
||||
}
|
||||
|
||||
// cookieSummaryResponse 是账号列表和账号详情共用的非敏感响应 DTO。
|
||||
type cookieSummaryResponse struct {
|
||||
// ID 是闲鱼账号的稳定标识。
|
||||
ID string `json:"id"`
|
||||
// HasCookie 表示数据库中存在可用账号记录。
|
||||
HasCookie bool `json:"has_cookie"`
|
||||
// Enabled 表示账号是否允许运行。
|
||||
Enabled bool `json:"enabled"`
|
||||
// AutoConfirm 表示是否自动确认订单。
|
||||
AutoConfirm bool `json:"auto_confirm"`
|
||||
// Remark 是账号备注。
|
||||
Remark string `json:"remark"`
|
||||
// PauseDuration 是自动回复暂停时长,单位为分钟。
|
||||
PauseDuration int `json:"pause_duration"`
|
||||
// PausedUntil 是暂停结束时间的 Unix 秒。
|
||||
PausedUntil int64 `json:"paused_until"`
|
||||
// Paused 表示账号当前是否仍处于暂停状态。
|
||||
Paused bool `json:"paused"`
|
||||
// ShowBrowser 表示密码登录流程是否允许显示浏览器。
|
||||
ShowBrowser bool `json:"show_browser"`
|
||||
// Username 是登录用户名,不包含登录密码。
|
||||
Username string `json:"username"`
|
||||
// Nickname 是平台账号昵称缓存。
|
||||
Nickname string `json:"nickname"`
|
||||
// AvatarURL 是平台账号头像地址。
|
||||
AvatarURL string `json:"avatar_url"`
|
||||
// LoginMethod 是最近一次成功登录方式。
|
||||
LoginMethod string `json:"login_method"`
|
||||
// LastLoginAt 是最近一次成功登录时间。
|
||||
LastLoginAt int64 `json:"last_login_at"`
|
||||
// ProfileError 是资料刷新错误;当前列表接口保留为空字符串。
|
||||
ProfileError string `json:"profile_error"`
|
||||
// AIEnabled 表示账号级 AI 回复是否启用。
|
||||
AIEnabled bool `json:"ai_enabled"`
|
||||
// AutoRateEnabled 表示自动评价计划是否启用。
|
||||
AutoRateEnabled bool `json:"auto_rate_enabled"`
|
||||
// RateContent 是自动评价文案。
|
||||
RateContent string `json:"rate_content"`
|
||||
// AutoPolishEnabled 表示自动擦亮计划是否启用。
|
||||
AutoPolishEnabled bool `json:"auto_polish_enabled"`
|
||||
// PolishTime 是自动擦亮的本地时间。
|
||||
PolishTime string `json:"polish_time"`
|
||||
// LastRateScanAt 是最近一次自动评价扫描时间。
|
||||
LastRateScanAt int64 `json:"last_rate_scan_at"`
|
||||
// LastPolishDate 是最近一次自动擦亮日期。
|
||||
LastPolishDate string `json:"last_polish_date"`
|
||||
// LastPolishAt 是最近一次自动擦亮时间。
|
||||
LastPolishAt int64 `json:"last_polish_at"`
|
||||
}
|
||||
|
||||
// writeErrRequest 写带请求追踪标识的统一错误响应。
|
||||
func writeErrRequest(w http.ResponseWriter, r *http.Request, status int, msg string) {
|
||||
writeErrCode(w, status, "", msg, middleware.GetReqID(r.Context()))
|
||||
}
|
||||
|
||||
// writeErrCode 写指定机器可读错误码和可选请求追踪标识的统一错误响应。
|
||||
func writeErrCode(w http.ResponseWriter, status int, code, msg, requestID string) {
|
||||
if code == "" && requestID == "" {
|
||||
// payload 是兼容历史内部调用的统一错误对象。
|
||||
payload := unifiedErrorPayload(msg)
|
||||
payload["code"] = httpapi.CodeForStatus(status)
|
||||
writeJSON(w, status, payload)
|
||||
return
|
||||
}
|
||||
httpapi.WriteError(w, status, code, msg, requestID)
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"xianyu-go/internal/httpapi"
|
||||
)
|
||||
|
||||
// TestAPIContractHealth 验证健康检查使用具名 DTO,并在正常状态返回完整构建信息。
|
||||
func TestAPIContractHealth(t *testing.T) {
|
||||
// srv 是带可用 SQLite 数据库的 HTTP 测试服务。
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
// req 是无需认证的健康检查请求。
|
||||
req := httptest.NewRequest(http.MethodGet, "/health", nil)
|
||||
// rec 是捕获健康检查响应的测试记录器。
|
||||
rec := httptest.NewRecorder()
|
||||
srv.Router().ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("health status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
// response 是反序列化后的健康检查具名 DTO。
|
||||
var response healthResponse
|
||||
// decodeErr 表示健康检查响应 JSON 反序列化失败的原因。
|
||||
if decodeErr := json.Unmarshal(rec.Body.Bytes(), &response); decodeErr != nil {
|
||||
t.Fatalf("decode health response: %v", decodeErr)
|
||||
}
|
||||
if response.Status != "ok" || response.Database != "ok" || response.Version == "" {
|
||||
t.Fatalf("health response=%+v", response)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAPIContractAuthenticationError 验证未认证请求返回统一错误 DTO 和请求追踪标识。
|
||||
func TestAPIContractAuthenticationError(t *testing.T) {
|
||||
// srv 是用于验证认证边界的 HTTP 测试服务。
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
// req 是没有 session cookie 的账号列表请求。
|
||||
req := httptest.NewRequest(http.MethodGet, "/cookies/details", nil)
|
||||
// rec 是捕获认证失败响应的测试记录器。
|
||||
rec := httptest.NewRecorder()
|
||||
srv.Router().ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("unauthorized status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
// response 是认证失败的统一错误 DTO。
|
||||
var response httpapi.ErrorResponse
|
||||
// decodeErr 表示认证错误响应 JSON 反序列化失败的原因。
|
||||
if decodeErr := json.Unmarshal(rec.Body.Bytes(), &response); decodeErr != nil {
|
||||
t.Fatalf("decode auth error: %v", decodeErr)
|
||||
}
|
||||
if response.Code != httpapi.CodeUnauthorized || response.Message != "未授权访问" || response.RequestID == "" {
|
||||
t.Fatalf("auth error response=%+v", response)
|
||||
}
|
||||
if strings.Contains(rec.Body.String(), `"detail"`) || strings.Contains(rec.Body.String(), `"msg"`) {
|
||||
t.Fatalf("auth response contains legacy error alias: %s", rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// TestAPIContractLoginFailure 验证错误密码不再使用 HTTP 200 加 success=false 表示失败。
|
||||
func TestAPIContractLoginFailure(t *testing.T) {
|
||||
// srv 是用于验证登录失败契约的 HTTP 测试服务。
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
// req 是使用错误密码的登录请求。
|
||||
req := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(`{"username":"admin","password":"wrong"}`))
|
||||
// rec 是捕获登录失败响应的测试记录器。
|
||||
rec := httptest.NewRecorder()
|
||||
srv.Router().ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("login failure status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
// response 是登录失败的统一错误 DTO。
|
||||
var response httpapi.ErrorResponse
|
||||
// decodeErr 表示登录错误响应 JSON 反序列化失败的原因。
|
||||
if decodeErr := json.Unmarshal(rec.Body.Bytes(), &response); decodeErr != nil {
|
||||
t.Fatalf("decode login error: %v", decodeErr)
|
||||
}
|
||||
if response.Code != "authentication_failed" || response.Message != "用户名或密码错误" {
|
||||
t.Fatalf("login error response=%+v", response)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAPIContractAccountList 验证账号列表返回具名非敏感 DTO,且不暴露 Cookie 或密码字段。
|
||||
func TestAPIContractAccountList(t *testing.T) {
|
||||
// srv 是带模板账号数据的 HTTP 测试服务。
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
// handler 是当前测试使用的完整路由树。
|
||||
handler := srv.Router()
|
||||
// sessionCookie 是管理员登录后得到的认证会话。
|
||||
sessionCookie := loginHelper(t, handler)
|
||||
// req 是读取账号非敏感详情的认证请求。
|
||||
req := httptest.NewRequest(http.MethodGet, "/cookies/details", nil)
|
||||
req.AddCookie(sessionCookie)
|
||||
// rec 是捕获账号列表响应的测试记录器。
|
||||
rec := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("account list status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
// response 是账号列表具名 DTO 集合。
|
||||
var response []cookieSummaryResponse
|
||||
// decodeErr 表示账号列表响应 JSON 反序列化失败的原因。
|
||||
if decodeErr := json.Unmarshal(rec.Body.Bytes(), &response); decodeErr != nil {
|
||||
t.Fatalf("decode account list: %v", decodeErr)
|
||||
}
|
||||
if len(response) == 0 || response[0].ID == "" || !response[0].HasCookie {
|
||||
t.Fatalf("account list response=%+v", response)
|
||||
}
|
||||
if strings.Contains(rec.Body.String(), `"value"`) || strings.Contains(rec.Body.String(), `"password"`) {
|
||||
t.Fatalf("account list exposes credential field: %s", rec.Body.String())
|
||||
}
|
||||
}
|
||||
@@ -99,8 +99,8 @@ func (s *Server) login(w http.ResponseWriter, r *http.Request) {
|
||||
sid, user, err := s.Auth.Login(r.Context(), req.Username, req.Password)
|
||||
if err != nil || user == nil || sid == "" {
|
||||
s.loginLimiter.failure(clientIP, principal, time.Now())
|
||||
resp = loginResponse{Success: false, Message: "用户名或密码错误"}
|
||||
writeJSON(w, http.StatusOK, resp)
|
||||
writeErrCode(w, http.StatusUnauthorized, "authentication_failed",
|
||||
"用户名或密码错误", "")
|
||||
return
|
||||
}
|
||||
resp = loginResponse{
|
||||
@@ -116,15 +116,15 @@ func (s *Server) login(w http.ResponseWriter, r *http.Request) {
|
||||
user, err := s.Store.Users.GetByEmail(r.Context(), req.Email)
|
||||
if err != nil || user == nil {
|
||||
s.loginLimiter.failure(clientIP, principal, time.Now())
|
||||
resp = loginResponse{Success: false, Message: "邮箱或密码错误"}
|
||||
writeJSON(w, http.StatusOK, resp)
|
||||
writeErrCode(w, http.StatusUnauthorized, "authentication_failed",
|
||||
"邮箱或密码错误", "")
|
||||
return
|
||||
}
|
||||
sid, loginUser, lerr := s.Auth.Login(r.Context(), user.Username, req.Password)
|
||||
if lerr != nil || loginUser == nil || sid == "" {
|
||||
s.loginLimiter.failure(clientIP, principal, time.Now())
|
||||
resp = loginResponse{Success: false, Message: "邮箱或密码错误"}
|
||||
writeJSON(w, http.StatusOK, resp)
|
||||
writeErrCode(w, http.StatusUnauthorized, "authentication_failed",
|
||||
"邮箱或密码错误", "")
|
||||
return
|
||||
}
|
||||
resp = loginResponse{
|
||||
|
||||
@@ -357,7 +357,7 @@ func (s *Server) listCookies(w http.ResponseWriter, r *http.Request) {
|
||||
sess := auth.SessionFromContext(r.Context()) // sess 是当前认证会话。
|
||||
ids, err := s.Store.Cookies.ListOwnedIDs(r.Context(), sess.UserID) // ids 和 err 是账号 ID 列表及查询错误。
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "获取账号失败")
|
||||
writeErrRequest(w, r, http.StatusInternalServerError, "获取账号失败")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, ids)
|
||||
@@ -368,36 +368,36 @@ func (s *Server) listCookieDetails(w http.ResponseWriter, r *http.Request) {
|
||||
sess := auth.SessionFromContext(r.Context()) // sess 是当前认证会话。
|
||||
summaries, err := s.Store.Cookies.ListSummaries(r.Context(), sess.UserID) // summaries 和 err 是账号摘要及查询错误。
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "获取账号失败")
|
||||
writeErrRequest(w, r, http.StatusInternalServerError, "获取账号失败")
|
||||
return
|
||||
}
|
||||
result := make([]map[string]any, 0, len(summaries)) // result 是非敏感详情响应列表。
|
||||
for _, summary := range summaries { // summary 是当前账号的非敏感摘要。
|
||||
result := make([]cookieSummaryResponse, 0, len(summaries)) // result 是非敏感详情响应列表。
|
||||
for _, summary := range summaries { // summary 是当前账号的非敏感摘要。
|
||||
tasks, _ := s.Store.AccountTasks.Get(r.Context(), summary.ID) // tasks 是当前账号的自动化任务设置。
|
||||
result = append(result, map[string]any{
|
||||
"id": summary.ID,
|
||||
"has_cookie": true,
|
||||
"enabled": s.Store.Cookies.GetStatus(r.Context(), summary.ID),
|
||||
"auto_confirm": summary.AutoConfirm,
|
||||
"remark": summary.Remark,
|
||||
"pause_duration": summary.PauseDuration,
|
||||
"paused_until": summary.PausedUntil,
|
||||
"paused": summary.PausedUntil > time.Now().UTC().Unix(),
|
||||
"show_browser": summary.ShowBrowser,
|
||||
"username": summary.Username,
|
||||
"nickname": cachedCookieSummaryNickname(summary),
|
||||
"avatar_url": summary.AvatarURL,
|
||||
"login_method": summary.LoginMethod,
|
||||
"last_login_at": summary.LastLoginAt,
|
||||
"profile_error": "",
|
||||
"ai_enabled": false,
|
||||
"auto_rate_enabled": tasks.AutoRateEnabled,
|
||||
"rate_content": tasks.RateContent,
|
||||
"auto_polish_enabled": tasks.AutoPolishEnabled,
|
||||
"polish_time": tasks.PolishTime,
|
||||
"last_rate_scan_at": tasks.LastRateScanAt,
|
||||
"last_polish_date": tasks.LastPolishDate,
|
||||
"last_polish_at": tasks.LastPolishAt,
|
||||
result = append(result, cookieSummaryResponse{
|
||||
ID: summary.ID,
|
||||
HasCookie: true,
|
||||
Enabled: s.Store.Cookies.GetStatus(r.Context(), summary.ID),
|
||||
AutoConfirm: summary.AutoConfirm,
|
||||
Remark: summary.Remark,
|
||||
PauseDuration: summary.PauseDuration,
|
||||
PausedUntil: summary.PausedUntil,
|
||||
Paused: summary.PausedUntil > time.Now().UTC().Unix(),
|
||||
ShowBrowser: summary.ShowBrowser,
|
||||
Username: summary.Username,
|
||||
Nickname: cachedCookieSummaryNickname(summary),
|
||||
AvatarURL: summary.AvatarURL,
|
||||
LoginMethod: summary.LoginMethod,
|
||||
LastLoginAt: summary.LastLoginAt,
|
||||
ProfileError: "",
|
||||
AIEnabled: false,
|
||||
AutoRateEnabled: tasks.AutoRateEnabled,
|
||||
RateContent: tasks.RateContent,
|
||||
AutoPolishEnabled: tasks.AutoPolishEnabled,
|
||||
PolishTime: tasks.PolishTime,
|
||||
LastRateScanAt: tasks.LastRateScanAt,
|
||||
LastPolishDate: tasks.LastPolishDate,
|
||||
LastPolishAt: tasks.LastPolishAt,
|
||||
})
|
||||
}
|
||||
writeJSON(w, http.StatusOK, result)
|
||||
|
||||
@@ -18,14 +18,14 @@ func writeJSON(w http.ResponseWriter, status int, v any) {
|
||||
_ = json.NewEncoder(w).Encode(v)
|
||||
}
|
||||
|
||||
// errDetail 构造 {"detail": msg} 错误体。
|
||||
func errDetail(msg string) map[string]any {
|
||||
return map[string]any{"detail": msg}
|
||||
// unifiedErrorPayload 构造统一 code/message 错误体,供无请求上下文的内部出口使用。
|
||||
func unifiedErrorPayload(msg string) map[string]any {
|
||||
return map[string]any{"code": "internal_error", "message": msg}
|
||||
}
|
||||
|
||||
// writeErr 写错误响应。
|
||||
// writeErr 写统一错误响应。
|
||||
func writeErr(w http.ResponseWriter, status int, msg string) {
|
||||
writeJSON(w, status, errDetail(msg))
|
||||
writeErrCode(w, status, "", msg, "")
|
||||
}
|
||||
|
||||
// decodeJSON 解析请求体 JSON。
|
||||
|
||||
+11
-11
@@ -291,11 +291,11 @@ func (s *Server) mountDirSPA(r chi.Router) {
|
||||
// SPA catch-all:非 API 的 GET 请求返回 index.html。
|
||||
r.Get("/*", func(w http.ResponseWriter, r *http.Request) {
|
||||
if isAPIPath(r.URL.Path) {
|
||||
writeJSON(w, http.StatusNotFound, errDetail("接口不存在"))
|
||||
writeErrRequest(w, r, http.StatusNotFound, "接口不存在")
|
||||
return
|
||||
}
|
||||
if _, err := os.Stat(indexFile); err != nil {
|
||||
writeJSON(w, http.StatusNotFound, errDetail("前端未构建"))
|
||||
writeErrRequest(w, r, http.StatusNotFound, "前端未构建")
|
||||
return
|
||||
}
|
||||
setNoStore(w)
|
||||
@@ -314,12 +314,12 @@ func (s *Server) mountFSSPA(r chi.Router, staticFS fs.FS) {
|
||||
|
||||
r.Get("/*", func(w http.ResponseWriter, r *http.Request) {
|
||||
if isAPIPath(r.URL.Path) {
|
||||
writeJSON(w, http.StatusNotFound, errDetail("接口不存在"))
|
||||
writeErrRequest(w, r, http.StatusNotFound, "接口不存在")
|
||||
return
|
||||
}
|
||||
index, err := fs.ReadFile(staticFS, "index.html")
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusNotFound, errDetail("前端未构建"))
|
||||
writeErrRequest(w, r, http.StatusNotFound, "前端未构建")
|
||||
return
|
||||
}
|
||||
setNoStore(w)
|
||||
@@ -362,15 +362,15 @@ func (s *Server) health(w http.ResponseWriter, r *http.Request) {
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
|
||||
defer cancel()
|
||||
if s.Store == nil || s.Store.DB == nil || s.Store.DB.PingContext(ctx) != nil {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]any{"status": "degraded", "database": "unavailable"})
|
||||
writeJSON(w, http.StatusServiceUnavailable, healthResponse{Status: "degraded", Database: "unavailable"})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"status": "ok",
|
||||
"database": "ok",
|
||||
"version": appversion.Version,
|
||||
"commit": appversion.ShortCommit(),
|
||||
"build_time": appversion.BuildTime,
|
||||
writeJSON(w, http.StatusOK, healthResponse{
|
||||
Status: "ok",
|
||||
Database: "ok",
|
||||
Version: appversion.Version,
|
||||
Commit: appversion.ShortCommit(),
|
||||
BuildTime: appversion.BuildTime,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user