ldap-1-backend/middleware/OperationLogMiddleware.go

71 lines
1.6 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package middleware
import (
"strings"
"time"
"github.com/eryajf-world/go-ldap-admin/config"
"github.com/eryajf-world/go-ldap-admin/model"
"github.com/eryajf-world/go-ldap-admin/public/tools"
"github.com/eryajf-world/go-ldap-admin/service/isql"
"github.com/gin-gonic/gin"
)
// 操作日志channel
var OperationLogChan = make(chan *model.OperationLog, 30)
func OperationLogMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
// 开始时间
startTime := time.Now()
// 处理请求
c.Next()
// 结束时间
endTime := time.Now()
// 执行耗时
timeCost := endTime.Sub(startTime).Milliseconds()
// 获取当前登录用户
var username string
ctxUser, exists := c.Get("user")
if !exists {
username = "未登录"
}
user, ok := ctxUser.(model.User)
if !ok {
username = "未登录"
}
username = user.Username
// 获取访问路径
path := strings.TrimPrefix(c.FullPath(), "/"+config.Conf.System.UrlPathPrefix)
// 请求方式
method := c.Request.Method
// 获取接口描述
api := new(model.Api)
_ = isql.Api.Find(tools.H{"path": path, "method": method}, api)
operationLog := model.OperationLog{
Username: username,
Ip: c.ClientIP(),
IpLocation: "",
Method: method,
Path: path,
Remark: api.Remark,
Status: c.Writer.Status(),
StartTime: startTime,
TimeCost: timeCost,
//UserAgent: c.Request.UserAgent(),
}
// 最好是将日志发送到rabbitmq或者kafka中
// 这里是发送到channel中开启3个goroutine处理
OperationLogChan <- &operationLog
}
}