session.go 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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. "v2ray.com/core/common/errors"
  7. )
  8. // ID of a session.
  9. type ID uint32
  10. // NewID generates a new ID. The generated ID is high likely to be unique, but not cryptographically secure.
  11. // The generated ID will never be 0.
  12. func NewID() ID {
  13. for {
  14. id := ID(rand.Uint32())
  15. if id != 0 {
  16. return id
  17. }
  18. }
  19. }
  20. type sessionKey int
  21. const (
  22. idSessionKey sessionKey = iota
  23. )
  24. // ContextWithID returns a new context with the given ID.
  25. func ContextWithID(ctx context.Context, id ID) context.Context {
  26. return context.WithValue(ctx, idSessionKey, id)
  27. }
  28. // IDFromContext returns ID in this context, or 0 if not contained.
  29. func IDFromContext(ctx context.Context) ID {
  30. if id, ok := ctx.Value(idSessionKey).(ID); ok {
  31. return id
  32. }
  33. return 0
  34. }
  35. func ExportIDToError(ctx context.Context) errors.ExportOption {
  36. id := IDFromContext(ctx)
  37. return func(h *errors.ExportOptionHolder) {
  38. h.SessionID = uint32(id)
  39. }
  40. }