31 lines
841 B
Go
31 lines
841 B
Go
package middleware
|
|
|
|
import (
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/google/uuid"
|
|
|
|
mygolog "github.com/dhao2001/mygo/internal/log"
|
|
)
|
|
|
|
// RequestID returns a Gin middleware that ensures every request has a
|
|
// request ID. If the client sends X-Request-ID, it is reused; otherwise a
|
|
// new UUID v4 is generated. The ID is injected into both the Go
|
|
// context.Context (for slog) and the Gin context (for handler access).
|
|
func RequestID() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
reqID := c.GetHeader("X-Request-ID")
|
|
if reqID == "" {
|
|
reqID = uuid.NewString()
|
|
}
|
|
|
|
// Inject into Go context for slog.*Context calls.
|
|
c.Request = c.Request.WithContext(mygolog.WithRequestID(c.Request.Context(), reqID))
|
|
|
|
// Also set in Gin context for direct access.
|
|
c.Set("req_id", reqID)
|
|
c.Header("X-Request-ID", reqID)
|
|
|
|
c.Next()
|
|
}
|
|
}
|