Add structured logging with request ID middleware

This commit is contained in:
2026-07-04 16:24:37 +08:00
parent 1dfccf513a
commit 53bd473861
3 changed files with 158 additions and 0 deletions
+30
View File
@@ -0,0 +1,30 @@
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()
}
}