| package logging |
|
|
| import ( |
| "context" |
| "crypto/rand" |
| "encoding/hex" |
|
|
| "github.com/gin-gonic/gin" |
| ) |
|
|
| |
| type requestIDKey struct{} |
|
|
| |
| const ginRequestIDKey = "__request_id__" |
|
|
| |
| func GenerateRequestID() string { |
| b := make([]byte, 4) |
| if _, err := rand.Read(b); err != nil { |
| return "00000000" |
| } |
| return hex.EncodeToString(b) |
| } |
|
|
| |
| func WithRequestID(ctx context.Context, requestID string) context.Context { |
| return context.WithValue(ctx, requestIDKey{}, requestID) |
| } |
|
|
| |
| |
| func GetRequestID(ctx context.Context) string { |
| if ctx == nil { |
| return "" |
| } |
| if id, ok := ctx.Value(requestIDKey{}).(string); ok { |
| return id |
| } |
| return "" |
| } |
|
|
| |
| func SetGinRequestID(c *gin.Context, requestID string) { |
| if c != nil { |
| c.Set(ginRequestIDKey, requestID) |
| } |
| } |
|
|
| |
| func GetGinRequestID(c *gin.Context) string { |
| if c == nil { |
| return "" |
| } |
| if id, exists := c.Get(ginRequestIDKey); exists { |
| if s, ok := id.(string); ok { |
| return s |
| } |
| } |
| return "" |
| } |
|
|