id.go 512 B

1234567891011121314151617181920212223242526272829303132
  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 context.WithValue(ctx, (*idKey)(nil), ID{
  18. ID: rand.Uint32(),
  19. CreatedAt: time.Now(),
  20. })
  21. }
  22. func IDFromContext(ctx context.Context) (ID, bool) {
  23. id, loaded := ctx.Value((*idKey)(nil)).(ID)
  24. return id, loaded
  25. }