first commit
This commit is contained in:
@@ -0,0 +1,37 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const requestIDKey ctxKey = "requestID"
|
||||
|
||||
// RequestID 从请求头取 X-Request-ID,没有则生成 UUID。
|
||||
// 注入 context 并写入响应头,便于全链路追踪。
|
||||
func RequestID() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
rid := c.GetHeader("X-Request-ID")
|
||||
if rid == "" {
|
||||
rid = uuid.New().String()
|
||||
}
|
||||
|
||||
// 写入 gin context(供 handler 取用)
|
||||
c.Set("requestID", rid)
|
||||
// 写入 request context(供 service/dao 的 slog 取用)
|
||||
ctx := context.WithValue(c.Request.Context(), requestIDKey, rid)
|
||||
c.Request = c.Request.WithContext(ctx)
|
||||
// 响应头
|
||||
c.Header("X-Request-ID", rid)
|
||||
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// GetRequestID 从 context 取出 request-id。
|
||||
func GetRequestID(ctx context.Context) string {
|
||||
rid, _ := ctx.Value(requestIDKey).(string)
|
||||
return rid
|
||||
}
|
||||
Reference in New Issue
Block a user