request_id.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package middleware
  2. import (
  3. "net/http"
  4. "regexp"
  5. "strings"
  6. "github.com/go-admin-team/go-admin-core/logger"
  7. "github.com/go-admin-team/go-admin-core/sdk/pkg"
  8. "go.opentelemetry.io/otel"
  9. "go.opentelemetry.io/otel/propagation"
  10. "go.opentelemetry.io/otel/trace"
  11. "github.com/gin-gonic/gin"
  12. "github.com/google/uuid"
  13. )
  14. // RequestId 自动增加requestId
  15. func RequestId(trafficKey string) gin.HandlerFunc {
  16. return func(c *gin.Context) {
  17. if c.Request.Method == http.MethodOptions {
  18. c.Next()
  19. return
  20. }
  21. prop := otel.GetTextMapPropagator()
  22. ctx := prop.Extract(c.Request.Context(), propagation.HeaderCarrier(c.Request.Header))
  23. span := trace.SpanFromContext(ctx)
  24. requestId := ""
  25. if span.SpanContext().IsValid() {
  26. requestId = span.SpanContext().TraceID().String()
  27. }
  28. if requestId == "" {
  29. requestId = c.GetHeader(trafficKey)
  30. if requestId == "" {
  31. requestId = c.GetHeader(strings.ToLower(trafficKey))
  32. }
  33. if requestId == "" {
  34. requestId = uuid.New().String()
  35. }
  36. }
  37. if valid, _ := regexp.Match("[0-9A-Za-z]+", []byte(requestId)); valid {
  38. c.Request.Header.Set(trafficKey, requestId)
  39. c.Set(trafficKey, requestId)
  40. c.Set(pkg.LoggerKey,
  41. logger.NewHelper(logger.DefaultLogger).
  42. WithFields(map[string]interface{}{
  43. trafficKey: requestId,
  44. }))
  45. }
  46. c.Next()
  47. }
  48. }