feat(server): add request ID middleware

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.
This commit is contained in:
zenfun
2025-12-13 22:24:37 +08:00
parent 67df74e09a
commit a6b4306d08
2 changed files with 36 additions and 0 deletions

View File

@@ -0,0 +1,35 @@
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[:])
}