mirror of
https://github.com/EZ-Api/ez-api.git
synced 2026-01-13 17:47:51 +00:00
Add request ID middleware to trace requests through the system. The middleware checks for existing X-Request-ID headers, generates a new UUID if not present, and sets the ID in both request/response headers and Gin context.
36 lines
769 B
Go
36 lines
769 B
Go
package middleware
|
|
|
|
import (
|
|
"crypto/rand"
|
|
"encoding/hex"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
// RequestID ensures every request has an X-Request-ID and echoes it back to the client.
|
|
func RequestID() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
id := strings.TrimSpace(c.GetHeader("X-Request-ID"))
|
|
if id == "" {
|
|
id = strings.TrimSpace(c.GetHeader("X-Request-Id"))
|
|
}
|
|
if id == "" {
|
|
id = newRequestID()
|
|
}
|
|
c.Request.Header.Set("X-Request-ID", id)
|
|
c.Writer.Header().Set("X-Request-ID", id)
|
|
c.Set("request_id", id)
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
func newRequestID() string {
|
|
var b [16]byte
|
|
if _, err := rand.Read(b[:]); err != nil {
|
|
return hex.EncodeToString([]byte(time.Now().Format(time.RFC3339Nano)))
|
|
}
|
|
return hex.EncodeToString(b[:])
|
|
}
|