requestid.go 680 B

1234567891011121314151617181920212223242526272829
  1. package middleware
  2. import (
  3. "github.com/gin-gonic/gin"
  4. "github.com/google/uuid"
  5. )
  6. const (
  7. // XRequestIDKey defines X-Request-ID key string.
  8. XRequestIDKey = "X-Request-ID"
  9. )
  10. // RequestID is a middleware that injects a 'X-Request-ID' into the context and request/response header of each request.
  11. func RequestID() gin.HandlerFunc {
  12. return func(c *gin.Context) {
  13. // Check for incoming header, use it if exists
  14. rid := c.GetHeader(XRequestIDKey)
  15. if rid == "" {
  16. rid = uuid.Must(uuid.NewV6()).String()
  17. c.Request.Header.Set(XRequestIDKey, rid)
  18. c.Set(XRequestIDKey, rid)
  19. }
  20. // Set XRequestIDKey header
  21. c.Writer.Header().Set(XRequestIDKey, rid)
  22. c.Next()
  23. }
  24. }