request-id.go 418 B

123456789101112131415161718
  1. package middleware
  2. import (
  3. "context"
  4. "github.com/gin-gonic/gin"
  5. "one-api/common"
  6. )
  7. func RequestId() func(c *gin.Context) {
  8. return func(c *gin.Context) {
  9. id := common.GetTimeString() + common.GetRandomString(8)
  10. c.Set(common.RequestIdKey, id)
  11. ctx := context.WithValue(c.Request.Context(), common.RequestIdKey, id)
  12. c.Request = c.Request.WithContext(ctx)
  13. c.Header(common.RequestIdKey, id)
  14. c.Next()
  15. }
  16. }