2022-06-30 21:27:56 +08:00
|
|
|
package log
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"context"
|
|
|
|
|
"math/rand"
|
2023-03-29 13:07:08 +08:00
|
|
|
"time"
|
2022-06-30 21:27:56 +08:00
|
|
|
)
|
|
|
|
|
|
2026-05-11 00:59:35 +03:00
|
|
|
type (
|
|
|
|
|
idKey struct{}
|
|
|
|
|
muxIdKey struct{}
|
|
|
|
|
hwidKey struct{}
|
|
|
|
|
)
|
2022-07-01 19:34:02 +08:00
|
|
|
|
2023-03-29 13:07:08 +08:00
|
|
|
type ID struct {
|
|
|
|
|
ID uint32
|
|
|
|
|
CreatedAt time.Time
|
|
|
|
|
}
|
|
|
|
|
|
2022-07-12 15:17:29 +08:00
|
|
|
func ContextWithNewID(ctx context.Context) context.Context {
|
2025-03-14 17:07:17 +08:00
|
|
|
return ContextWithID(ctx, ID{
|
2023-03-29 13:07:08 +08:00
|
|
|
ID: rand.Uint32(),
|
|
|
|
|
CreatedAt: time.Now(),
|
|
|
|
|
})
|
2022-06-30 21:27:56 +08:00
|
|
|
}
|
|
|
|
|
|
2025-03-14 17:07:17 +08:00
|
|
|
func ContextWithID(ctx context.Context, id ID) context.Context {
|
|
|
|
|
return context.WithValue(ctx, (*idKey)(nil), id)
|
|
|
|
|
}
|
|
|
|
|
|
2023-03-29 13:07:08 +08:00
|
|
|
func IDFromContext(ctx context.Context) (ID, bool) {
|
|
|
|
|
id, loaded := ctx.Value((*idKey)(nil)).(ID)
|
2022-07-12 15:17:29 +08:00
|
|
|
return id, loaded
|
2022-06-30 21:27:56 +08:00
|
|
|
}
|
2026-02-26 22:44:31 +03:00
|
|
|
|
|
|
|
|
func ContextWithNewMuxID(ctx context.Context) context.Context {
|
|
|
|
|
return ContextWithMuxID(ctx, ID{
|
|
|
|
|
ID: rand.Uint32(),
|
|
|
|
|
CreatedAt: time.Now(),
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func ContextWithMuxID(ctx context.Context, id ID) context.Context {
|
|
|
|
|
return context.WithValue(ctx, (*muxIdKey)(nil), id)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func MuxIDFromContext(ctx context.Context) (ID, bool) {
|
|
|
|
|
id, loaded := ctx.Value((*muxIdKey)(nil)).(ID)
|
|
|
|
|
return id, loaded
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func ContextWithHWID(ctx context.Context, id ID) context.Context {
|
|
|
|
|
return context.WithValue(ctx, (*hwidKey)(nil), id)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func HWIDFromContext(ctx context.Context) (ID, bool) {
|
|
|
|
|
id, loaded := ctx.Value((*hwidKey)(nil)).(ID)
|
|
|
|
|
return id, loaded
|
|
|
|
|
}
|