id.go 611 B

123456789101112131415161718192021222324252627282930313233343536
  1. package log
  2. import (
  3. "context"
  4. "math/rand"
  5. "time"
  6. "github.com/sagernet/sing/common/random"
  7. )
  8. func init() {
  9. random.InitializeSeed()
  10. }
  11. type idKey struct{}
  12. type ID struct {
  13. ID uint32
  14. CreatedAt time.Time
  15. }
  16. func ContextWithNewID(ctx context.Context) context.Context {
  17. return ContextWithID(ctx, ID{
  18. ID: rand.Uint32(),
  19. CreatedAt: time.Now(),
  20. })
  21. }
  22. func ContextWithID(ctx context.Context, id ID) context.Context {
  23. return context.WithValue(ctx, (*idKey)(nil), id)
  24. }
  25. func IDFromContext(ctx context.Context) (ID, bool) {
  26. id, loaded := ctx.Value((*idKey)(nil)).(ID)
  27. return id, loaded
  28. }