API / internal /api /middleware /correlation.go
sshinmen's picture
Clean deploy to HF Space
bf9e111
Raw
History Blame
1.6 kB
// Package middleware provides HTTP middleware components for the CLI Proxy API server.
// This file contains correlation ID middleware for request tracing.
package middleware
import (
"github.com/gin-gonic/gin"
"github.com/google/uuid"
)
const (
// CorrelationIDHeader is the HTTP header name for correlation IDs
CorrelationIDHeader = "X-Correlation-ID"
// CorrelationIDContextKey is the context key for correlation IDs
CorrelationIDContextKey = "correlation_id"
)
// CorrelationIDMiddleware creates a Gin middleware that ensures every request
// has a correlation ID for distributed tracing. It checks for an existing ID
// in the request headers and generates a new one if not present.
func CorrelationIDMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
// Check for existing correlation ID in header
correlationID := c.GetHeader(CorrelationIDHeader)
// Generate new ID if not present
if correlationID == "" {
correlationID = generateCorrelationID()
}
// Store in context
c.Set(CorrelationIDContextKey, correlationID)
// Add to response headers
c.Header(CorrelationIDHeader, correlationID)
c.Next()
}
}
// GetCorrelationID retrieves the correlation ID from the Gin context.
// Returns empty string if no correlation ID is found.
func GetCorrelationID(c *gin.Context) string {
if id, exists := c.Get(CorrelationIDContextKey); exists {
if str, ok := id.(string); ok {
return str
}
}
return ""
}
// generateCorrelationID generates a new unique correlation ID.
func generateCorrelationID() string {
return uuid.New().String()
}