Files
nl-blogs/server/middleware/access_log.go
2026-01-16 09:32:46 +08:00

45 lines
1.0 KiB
Go

package middleware
import (
"time"
"github.com/gin-gonic/gin"
"github.com/niangaodev/art-code/models"
"github.com/niangaodev/art-code/repositories"
"github.com/niangaodev/art-code/utils"
)
// AccessLogMiddleware 访问日志中间件 (用于流量统计)
func AccessLogMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
start := time.Now()
c.Next()
// 过滤静态资源和API调用
// 这里只记录主要页面访问,或者我们可以记录所有非静态资源
// 简化起见,记录所有请求,分析时再过滤
// 获取IP
ip := c.ClientIP()
// 获取归属地 (需要先初始化ip2region)
region := utils.GetRegion(ip)
log := &models.AccessLog{
IP: ip,
UserAgent: c.Request.UserAgent(),
Path: c.Request.URL.Path,
Method: c.Request.Method,
StatusCode: c.Writer.Status(),
ResponseTime: time.Since(start).Milliseconds(),
Region: region,
}
// 异步入库
go func() {
repositories.CreateAccessLog(log)
}()
}
}