31 lines
491 B
Go
31 lines
491 B
Go
package middleware
|
|
|
|
import (
|
|
"crypto/rand"
|
|
"encoding/hex"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
const RequestIDKey = "X-Request-ID"
|
|
|
|
func newRequestID() string {
|
|
b := make([]byte, 16)
|
|
if _, err := rand.Read(b); err != nil {
|
|
return "unknown"
|
|
}
|
|
return hex.EncodeToString(b)
|
|
}
|
|
|
|
func RequestID() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
id := c.GetHeader(RequestIDKey)
|
|
if id == "" {
|
|
id = newRequestID()
|
|
}
|
|
c.Set(RequestIDKey, id)
|
|
c.Header(RequestIDKey, id)
|
|
c.Next()
|
|
}
|
|
}
|