Co-authored-by: Jeffrey Smith <jasafpro@gmail.com> Co-committed-by: Jeffrey Smith <jasafpro@gmail.com>
29 lines
732 B
Go
29 lines
732 B
Go
package middleware
|
|
|
|
import (
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/google/uuid"
|
|
)
|
|
|
|
const (
|
|
// RequestIDKey is the Gin context key for the request ID.
|
|
RequestIDKey = "request_id"
|
|
// RequestIDHeader is the HTTP header used to propagate request IDs.
|
|
RequestIDHeader = "X-Request-Id"
|
|
)
|
|
|
|
// RequestID generates a UUID per request and sets it in the Gin context
|
|
// and response header. If the incoming request already carries an
|
|
// X-Request-Id header, it is preserved (useful for tracing across proxies).
|
|
func RequestID() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
id := c.GetHeader(RequestIDHeader)
|
|
if id == "" {
|
|
id = uuid.New().String()
|
|
}
|
|
c.Set(RequestIDKey, id)
|
|
c.Header(RequestIDHeader, id)
|
|
c.Next()
|
|
}
|
|
}
|