77 lines
1.6 KiB
Go
77 lines
1.6 KiB
Go
package service
|
|
|
|
import (
|
|
"fmt"
|
|
"go.uber.org/zap"
|
|
"net/http"
|
|
"rear/internal/model"
|
|
"rear/pkg/logger"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
// LoggerMiddleware 日志中间件
|
|
func LoggerMiddleware() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
start := time.Now()
|
|
path := c.Request.URL.Path
|
|
raw := c.Request.URL.RawQuery
|
|
|
|
// 处理请求
|
|
c.Next()
|
|
|
|
// 记录请求日志
|
|
latency := time.Since(start)
|
|
clientIP := c.ClientIP()
|
|
method := c.Request.Method
|
|
statusCode := c.Writer.Status()
|
|
|
|
if raw != "" {
|
|
path = path + "?" + raw
|
|
}
|
|
|
|
// 使用你的日志封装
|
|
logger.Info("HTTP Request",
|
|
zap.String("method", method),
|
|
zap.String("path", path),
|
|
zap.Int("status", statusCode),
|
|
zap.String("ip", clientIP),
|
|
zap.Duration("latency", latency),
|
|
zap.String("user_agent", c.Request.UserAgent()),
|
|
)
|
|
}
|
|
}
|
|
|
|
// ErrorHandlerMiddleware 错误处理中间件
|
|
func ErrorHandlerMiddleware() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
c.Next()
|
|
|
|
if len(c.Errors) > 0 {
|
|
err := c.Errors.Last()
|
|
|
|
// 使用格式化日志
|
|
logger.Errorf("Request error: %v", err.Err)
|
|
|
|
c.JSON(http.StatusInternalServerError, model.Response{
|
|
Code: http.StatusInternalServerError,
|
|
Message: "Internal server error",
|
|
})
|
|
}
|
|
}
|
|
}
|
|
|
|
// RequestIDMiddleware 请求ID中间件
|
|
func RequestIDMiddleware() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
requestID := c.GetHeader("X-Request-ID")
|
|
if requestID == "" {
|
|
requestID = fmt.Sprintf("%d", time.Now().UnixNano())
|
|
}
|
|
c.Header("X-Request-ID", requestID)
|
|
c.Set("request_id", requestID)
|
|
c.Next()
|
|
}
|
|
}
|