优化代码
This commit is contained in:
@@ -7,17 +7,19 @@ import (
|
||||
"git.huangwc.com/pig/pig-farm-controller/internal/infra/logs"
|
||||
"git.huangwc.com/pig/pig-farm-controller/internal/infra/models"
|
||||
"git.huangwc.com/pig/pig-farm-controller/internal/infra/repository"
|
||||
"github.com/gin-gonic/gin"
|
||||
// 移除对 "github.com/gin-gonic/gin" 的直接依赖
|
||||
)
|
||||
|
||||
const (
|
||||
// ContextUserKey 是存储在 gin.Context 中的用户对象的键名
|
||||
ContextUserKey = "user"
|
||||
)
|
||||
// RequestContext 封装了审计日志所需的请求上下文信息
|
||||
type RequestContext struct {
|
||||
ClientIP string
|
||||
HTTPPath string
|
||||
HTTPMethod string
|
||||
}
|
||||
|
||||
// Service 定义了审计服务的接口
|
||||
type Service interface {
|
||||
LogAction(c *gin.Context, actionType, description string, targetResource interface{}, status string, resultDetails string)
|
||||
LogAction(user *models.User, reqCtx RequestContext, actionType, description string, targetResource interface{}, status string, resultDetails string)
|
||||
}
|
||||
|
||||
// service 是 Service 接口的实现
|
||||
@@ -32,18 +34,10 @@ func NewService(repo repository.UserActionLogRepository, logger *logs.Logger) Se
|
||||
}
|
||||
|
||||
// LogAction 记录一个用户操作。它在一个新的 goroutine 中异步执行,以避免阻塞主请求。
|
||||
func (s *service) LogAction(c *gin.Context, actionType, description string, targetResource interface{}, status string, resultDetails string) {
|
||||
// 从 context 中获取预加载的用户信息
|
||||
userCtx, exists := c.Get(ContextUserKey)
|
||||
if !exists {
|
||||
// 如果上下文中没有用户信息(例如,在未认证的路由上调用了此函数),则不记录日志
|
||||
s.logger.Warnw("无法记录审计日志:上下文中缺少用户信息")
|
||||
return
|
||||
}
|
||||
|
||||
user, ok := userCtx.(*models.User)
|
||||
if !ok {
|
||||
s.logger.Errorw("无法记录审计日志:上下文中的用户对象类型不正确")
|
||||
func (s *service) LogAction(user *models.User, reqCtx RequestContext, actionType, description string, targetResource interface{}, status string, resultDetails string) {
|
||||
// 不再从 context 中获取用户信息,直接使用传入的 user 对象
|
||||
if user == nil {
|
||||
s.logger.Warnw("无法记录审计日志:传入的用户对象为 nil")
|
||||
return
|
||||
}
|
||||
|
||||
@@ -51,12 +45,12 @@ func (s *service) LogAction(c *gin.Context, actionType, description string, targ
|
||||
Time: time.Now(),
|
||||
UserID: user.ID,
|
||||
Username: user.Username, // 用户名快照
|
||||
SourceIP: c.ClientIP(),
|
||||
SourceIP: reqCtx.ClientIP,
|
||||
ActionType: actionType,
|
||||
Description: description,
|
||||
Status: status,
|
||||
HTTPPath: c.Request.URL.Path,
|
||||
HTTPMethod: c.Request.Method,
|
||||
HTTPPath: reqCtx.HTTPPath,
|
||||
HTTPMethod: reqCtx.HTTPMethod,
|
||||
ResultDetails: resultDetails,
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user