Files
ai_english/serve/internal/middleware/request_id.go
2025-11-17 14:09:17 +08:00

28 lines
530 B
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 (
"github.com/gin-gonic/gin"
"github.com/google/uuid"
)
// RequestID 为每个请求生成唯一ID
func RequestID() gin.HandlerFunc {
return func(c *gin.Context) {
// 尝试从请求头获取Request ID
requestID := c.GetHeader("X-Request-ID")
// 如果没有生成新的UUID
if requestID == "" {
requestID = uuid.New().String()
}
// 设置到上下文中
c.Set("request_id", requestID)
// 设置到响应头中
c.Header("X-Request-ID", requestID)
c.Next()
}
}