request_id.go 817 B

123456789101112131415161718192021222324252627282930313233343536
  1. package middleware
  2. import (
  3. "github.com/go-admin-team/go-admin-core/logger"
  4. "github.com/go-admin-team/go-admin-core/sdk/pkg"
  5. "net/http"
  6. "strings"
  7. "github.com/gin-gonic/gin"
  8. "github.com/google/uuid"
  9. )
  10. // RequestId 自动增加requestId
  11. func RequestId(trafficKey string) gin.HandlerFunc {
  12. return func(c *gin.Context) {
  13. if c.Request.Method == http.MethodOptions {
  14. c.Next()
  15. return
  16. }
  17. requestId := c.GetHeader(trafficKey)
  18. if requestId == "" {
  19. requestId = c.GetHeader(strings.ToLower(trafficKey))
  20. }
  21. if requestId == "" {
  22. requestId = uuid.New().String()
  23. }
  24. c.Request.Header.Set(trafficKey, requestId)
  25. c.Set(trafficKey, requestId)
  26. c.Set(pkg.LoggerKey,
  27. logger.NewHelper(logger.DefaultLogger).
  28. WithFields(map[string]interface{}{
  29. trafficKey: requestId,
  30. }))
  31. c.Next()
  32. }
  33. }