session.go 867 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. // Package session provides functions for sessions of incoming requests.
  2. package session // import "v2ray.com/core/common/session"
  3. import (
  4. "context"
  5. "math/rand"
  6. )
  7. // ID of a session.
  8. type ID uint32
  9. // NewID generates a new ID. The generated ID is high likely to be unique, but not cryptographically secure.
  10. // The generated ID will never be 0.
  11. func NewID() ID {
  12. for {
  13. id := ID(rand.Uint32())
  14. if id != 0 {
  15. return id
  16. }
  17. }
  18. }
  19. type sessionKey int
  20. const (
  21. idSessionKey sessionKey = iota
  22. )
  23. // ContextWithID returns a new context with the given ID.
  24. func ContextWithID(ctx context.Context, id ID) context.Context {
  25. return context.WithValue(ctx, idSessionKey, id)
  26. }
  27. // IDFromContext returns ID in this context, or 0 if not contained.
  28. func IDFromContext(ctx context.Context) ID {
  29. if id, ok := ctx.Value(idSessionKey).(ID); ok {
  30. return id
  31. }
  32. return 0
  33. }