完成任务3.1

This commit is contained in:
2025-10-30 16:35:54 +08:00
parent f2078ea54a
commit ff8a8d2b97
3 changed files with 63 additions and 53 deletions

View File

@@ -31,12 +31,13 @@ const (
// Response 定义统一的API响应结构体
type Response struct {
Code ResponseCode `json:"code"` // 业务状态码
Message string `json:"message"` // 提示信息
Data interface{} `json:"data"` // 业务数据
Code ResponseCode `json:"code"` // 业务状态码
Message string `json:"message"` // 提示信息
Data interface{} `json:"data,omitempty"` // 业务数据, omitempty表示如果为空则不序列化
}
// SendResponse 发送统一格式的JSON响应 (基础函数,不带审计)
// 所有的业务API都应该使用这个函数返回以确保HTTP状态码始终为200 OK。
func SendResponse(c echo.Context, code ResponseCode, message string, data interface{}) error {
return c.JSON(http.StatusOK, Response{
Code: code,
@@ -46,10 +47,20 @@ func SendResponse(c echo.Context, code ResponseCode, message string, data interf
}
// SendErrorResponse 发送统一格式的错误响应 (基础函数,不带审计)
// HTTP状态码为200 OK通过业务码表示错误。
func SendErrorResponse(c echo.Context, code ResponseCode, message string) error {
return SendResponse(c, code, message, nil)
}
// SendErrorWithStatus 发送带有指定HTTP状态码的错误响应。
// 这个函数主要用于中间件或特殊场景如认证失败在这些场景下需要返回非200的HTTP状态码。
func SendErrorWithStatus(c echo.Context, httpStatus int, code ResponseCode, message string) error {
return c.JSON(httpStatus, Response{
Code: code,
Message: message,
})
}
// --- 带审计功能的响应函数 ---
// setAuditDetails 是一个内部辅助函数,用于在 echo.Context 中设置业务相关的审计信息。