request_id.go 800 B

12345678910111213141516171819202122232425262728293031323334353637
  1. package middleware
  2. import (
  3. "net/http"
  4. "strings"
  5. "github.com/gin-gonic/gin"
  6. "github.com/google/uuid"
  7. log "gogs.baozhida.cn/zoie/OAuth-core/logger"
  8. "gogs.baozhida.cn/zoie/OAuth-core/pkg"
  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. log.NewHelper(log.DefaultLogger).
  28. WithFields(map[string]interface{}{
  29. trafficKey: requestId,
  30. }))
  31. c.Next()
  32. }
  33. }