context.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. It is unsupported to use this function to create a context that is suitable to invoke V2Ray's internal component
  26. in third party code, you shouldn't use //go:linkname to alias of this function into your own package and
  27. use this function in your third party code.
  28. For third party code, usage enabled by creating a context to interact with V2Ray's internal component is unsupported,
  29. and may break at any time.
  30. */
  31. func toContext(ctx context.Context, v *Instance) context.Context {
  32. if FromContext(ctx) != v {
  33. ctx = context.WithValue(ctx, v2rayKey, v)
  34. }
  35. return ctx
  36. }
  37. /* mustToContext returns ctx from the given context, or panics if not found that.
  38. It is unsupported to use this function to create a context that is suitable to invoke V2Ray's internal component
  39. in third party code, you shouldn't use //go:linkname to alias of this function into your own package and
  40. use this function in your third party code.
  41. For third party code, usage enabled by creating a context to interact with V2Ray's internal component is unsupported,
  42. and may break at any time.
  43. */
  44. func mustToContext(ctx context.Context, v *Instance) context.Context {
  45. if c := toContext(ctx, v); c != ctx {
  46. panic("V is not in context.")
  47. }
  48. return ctx
  49. }