File size: 1,597 Bytes
bf9e111 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | // 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()
}
|