package controller import ( "net/http" "git.huangwc.com/pig/pig-farm-controller/internal/app/middleware" "github.com/gin-gonic/gin" ) // --- 业务状态码 --- type ResponseCode int const ( // 成功状态码 (2000-2999) CodeSuccess ResponseCode = 2000 // 操作成功 CodeCreated ResponseCode = 2001 // 创建成功 // 客户端错误状态码 (4000-4999) CodeBadRequest ResponseCode = 4000 // 请求参数错误 CodeUnauthorized ResponseCode = 4001 // 未授权 CodeNotFound ResponseCode = 4004 // 资源未找到 CodeConflict ResponseCode = 4009 // 资源冲突 // 服务器错误状态码 (5000-5999) CodeInternalError ResponseCode = 5000 // 服务器内部错误 CodeServiceUnavailable ResponseCode = 5003 // 服务不可用 ) // --- 通用响应结构 --- // Response 定义统一的API响应结构体 type Response struct { Code ResponseCode `json:"code"` // 业务状态码 Message string `json:"message"` // 提示信息 Data interface{} `json:"data"` // 业务数据 } // SendResponse 发送统一格式的JSON响应 (基础函数,不带审计) func SendResponse(ctx *gin.Context, code ResponseCode, message string, data interface{}) { ctx.JSON(http.StatusOK, Response{ Code: code, Message: message, Data: data, }) } // SendErrorResponse 发送统一格式的错误响应 (基础函数,不带审计) func SendErrorResponse(ctx *gin.Context, code ResponseCode, message string) { SendResponse(ctx, code, message, nil) } // --- 带审计功能的响应函数 --- // setAuditDetails 是一个内部辅助函数,用于在 gin.Context 中设置业务相关的审计信息。 func setAuditDetails(c *gin.Context, actionType, description string, targetResource interface{}) { // 只有当 actionType 不为空时,才设置审计信息,这作为触发审计的标志 if actionType != "" { c.Set(middleware.ContextAuditActionType, actionType) c.Set(middleware.ContextAuditDescription, description) c.Set(middleware.ContextAuditTargetResource, targetResource) } } // SendSuccessWithAudit 发送成功的响应,并设置审计日志所需的信息。 // 这是控制器中用于记录成功操作并返回响应的首选函数。 func SendSuccessWithAudit(ctx *gin.Context, code ResponseCode, message string, data interface{}, actionType, description string, targetResource interface{}) { // 1. 设置审计信息 setAuditDetails(ctx, actionType, description, targetResource) // 2. 发送响应 SendResponse(ctx, code, message, data) } // SendErrorWithAudit 发送失败的响应,并设置审计日志所需的信息。 // 这是控制器中用于记录失败操作并返回响应的首选函数。 func SendErrorWithAudit(ctx *gin.Context, code ResponseCode, message string, actionType, description string, targetResource interface{}) { // 1. 设置审计信息 setAuditDetails(ctx, actionType, description, targetResource) // 2. 发送响应 SendErrorResponse(ctx, code, message) }