26 lines
608 B
Go
26 lines
608 B
Go
package logging
|
|
|
|
import "context"
|
|
|
|
type requestIDContextKey struct{}
|
|
|
|
// WithRequestID 把请求 ID 写入标准 context,供非 HTTP 层日志关联请求链路。
|
|
func WithRequestID(ctx context.Context, requestID string) context.Context {
|
|
if ctx == nil || requestID == "" {
|
|
return ctx
|
|
}
|
|
return context.WithValue(ctx, requestIDContextKey{}, requestID)
|
|
}
|
|
|
|
// RequestIDFromContext 从标准 context 读取请求 ID。
|
|
func RequestIDFromContext(ctx context.Context) string {
|
|
if ctx == nil {
|
|
return ""
|
|
}
|
|
value, ok := ctx.Value(requestIDContextKey{}).(string)
|
|
if !ok {
|
|
return ""
|
|
}
|
|
return value
|
|
}
|