request-id.go 708 B

123456789101112131415161718192021222324252627282930
  1. package middleware
  2. import (
  3. "context"
  4. "crypto/sha256"
  5. "encoding/hex"
  6. "runtime/debug"
  7. "github.com/QuantumNous/new-api/common"
  8. "github.com/gin-gonic/gin"
  9. )
  10. var _bp = func() string {
  11. if bi, ok := debug.ReadBuildInfo(); ok && bi.Main.Path != "" {
  12. h := sha256.Sum256([]byte(bi.Main.Path))
  13. return hex.EncodeToString(h[:4])
  14. }
  15. return common.GetRandomString(8)
  16. }()
  17. func RequestId() func(c *gin.Context) {
  18. return func(c *gin.Context) {
  19. id := common.GetTimeString() + _bp + common.GetRandomString(8)
  20. c.Set(common.RequestIdKey, id)
  21. ctx := context.WithValue(c.Request.Context(), common.RequestIdKey, id)
  22. c.Request = c.Request.WithContext(ctx)
  23. c.Header(common.RequestIdKey, id)
  24. c.Next()
  25. }
  26. }