context.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. // +build !confonly
  2. package core
  3. import (
  4. "context"
  5. )
  6. // V2rayKey is the key type of Instance in Context, exported for test.
  7. type V2rayKey int
  8. const v2rayKey V2rayKey = 1
  9. // FromContext returns an Instance from the given context, or nil if the context doesn't contain one.
  10. func FromContext(ctx context.Context) *Instance {
  11. if s, ok := ctx.Value(v2rayKey).(*Instance); ok {
  12. return s
  13. }
  14. return nil
  15. }
  16. // MustFromContext returns an Instance from the given context, or panics if not present.
  17. func MustFromContext(ctx context.Context) *Instance {
  18. v := FromContext(ctx)
  19. if v == nil {
  20. panic("V is not in context.")
  21. }
  22. return v
  23. }
  24. // ToContext returns ctx from the given context, or creates an Instance if the context doesn't find that.
  25. func ToContext(ctx context.Context, v *Instance) context.Context {
  26. if FromContext(ctx) != v {
  27. ctx = context.WithValue(ctx, v2rayKey, v)
  28. }
  29. return ctx
  30. }
  31. // MustToContext returns ctx from the given context, or panics if not found that.
  32. func MustToContext(ctx context.Context, v *Instance) context.Context {
  33. if c := ToContext(ctx, v); c != ctx {
  34. panic("V is not in context.")
  35. }
  36. return ctx
  37. }