完成任务2

This commit is contained in:
2025-10-30 16:19:24 +08:00
parent 7c5232e71b
commit c463875fba
5 changed files with 49 additions and 34 deletions

View File

@@ -4,7 +4,7 @@ import (
"net/http"
"git.huangwc.com/pig/pig-farm-controller/internal/infra/models"
"github.com/gin-gonic/gin"
"github.com/labstack/echo/v4"
)
// --- 业务状态码 ---
@@ -37,8 +37,8 @@ type Response struct {
}
// SendResponse 发送统一格式的JSON响应 (基础函数,不带审计)
func SendResponse(ctx *gin.Context, code ResponseCode, message string, data interface{}) {
ctx.JSON(http.StatusOK, Response{
func SendResponse(c echo.Context, code ResponseCode, message string, data interface{}) error {
return c.JSON(http.StatusOK, Response{
Code: code,
Message: message,
Data: data,
@@ -46,14 +46,14 @@ func SendResponse(ctx *gin.Context, code ResponseCode, message string, data inte
}
// SendErrorResponse 发送统一格式的错误响应 (基础函数,不带审计)
func SendErrorResponse(ctx *gin.Context, code ResponseCode, message string) {
SendResponse(ctx, code, message, nil)
func SendErrorResponse(c echo.Context, code ResponseCode, message string) error {
return SendResponse(c, code, message, nil)
}
// --- 带审计功能的响应函数 ---
// setAuditDetails 是一个内部辅助函数,用于在 gin.Context 中设置业务相关的审计信息。
func setAuditDetails(c *gin.Context, actionType, description string, targetResource interface{}) {
// setAuditDetails 是一个内部辅助函数,用于在 echo.Context 中设置业务相关的审计信息。
func setAuditDetails(c echo.Context, actionType, description string, targetResource interface{}) {
// 只有当 actionType 不为空时,才设置审计信息,这作为触发审计的标志
if actionType != "" {
c.Set(models.ContextAuditActionType.String(), actionType)
@@ -65,32 +65,32 @@ func setAuditDetails(c *gin.Context, actionType, description string, targetResou
// SendSuccessWithAudit 发送成功的响应,并设置审计日志所需的信息。
// 这是控制器中用于记录成功操作并返回响应的首选函数。
func SendSuccessWithAudit(
ctx *gin.Context, // Gin上下文用于处理HTTP请求和响应
c echo.Context, // Echo上下文用于处理HTTP请求和响应
code ResponseCode, // 业务状态码,表示操作结果
message string, // 提示信息,向用户展示操作结果的文本描述
data interface{}, // 业务数据,操作成功后返回的具体数据
actionType string, // 审计操作类型,例如"创建用户", "更新配置"
description string, // 审计描述,对操作的详细说明
targetResource interface{}, // 审计目标资源,被操作的资源对象或其标识
) {
) error {
// 1. 设置审计信息
setAuditDetails(ctx, actionType, description, targetResource)
setAuditDetails(c, actionType, description, targetResource)
// 2. 发送响应
SendResponse(ctx, code, message, data)
return SendResponse(c, code, message, data)
}
// SendErrorWithAudit 发送失败的响应,并设置审计日志所需的信息。
// 这是控制器中用于记录失败操作并返回响应的首选函数。
func SendErrorWithAudit(
ctx *gin.Context, // Gin上下文用于处理HTTP请求和响应
c echo.Context, // Echo上下文用于处理HTTP请求和响应
code ResponseCode, // 业务状态码,表示操作结果
message string, // 提示信息,向用户展示操作结果的文本描述
actionType string, // 审计操作类型,例如"登录失败", "删除失败"
description string, // 审计描述,对操作的详细说明
targetResource interface{}, // 审计目标资源,被操作的资源对象或其标识
) {
) error {
// 1. 设置审计信息
setAuditDetails(ctx, actionType, description, targetResource)
setAuditDetails(c, actionType, description, targetResource)
// 2. 发送响应
SendErrorResponse(ctx, code, message)
return SendErrorResponse(c, code, message)
}