context.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package core
  2. import (
  3. "context"
  4. )
  5. // V2rayKey is the key type of Instance in Context, exported for test.
  6. type v2rayKeyType int
  7. const v2rayKey v2rayKeyType = 1
  8. // FromContext returns an Instance from the given context, or nil if the context doesn't contain one.
  9. func FromContext(ctx context.Context) *Instance {
  10. if s, ok := ctx.Value(v2rayKey).(*Instance); ok {
  11. return s
  12. }
  13. return nil
  14. }
  15. // MustFromContext returns an Instance from the given context, or panics if not present.
  16. func MustFromContext(ctx context.Context) *Instance {
  17. v := FromContext(ctx)
  18. if v == nil {
  19. panic("V is not in context.")
  20. }
  21. return v
  22. }
  23. /* toContext returns ctx from the given context, or creates an Instance if the context doesn't find that.
  24. It is unsupported to use this function to create a context that is suitable to invoke V2Ray's internal component
  25. in third party code, you shouldn't use //go:linkname to alias of this function into your own package and
  26. use this function in your third party code.
  27. For third party code, usage enabled by creating a context to interact with V2Ray's internal component is unsupported,
  28. and may break at any time.
  29. */
  30. func toContext(ctx context.Context, v *Instance) context.Context {
  31. if FromContext(ctx) != v {
  32. ctx = context.WithValue(ctx, v2rayKey, v)
  33. }
  34. return ctx
  35. }
  36. /*ToBackgroundDetachedContext create a detached context from another context
  37. Internal API
  38. */
  39. func ToBackgroundDetachedContext(ctx context.Context) context.Context {
  40. return &temporaryValueDelegationFix{context.Background(), ctx}
  41. }
  42. type temporaryValueDelegationFix struct {
  43. context.Context
  44. value context.Context
  45. }
  46. func (t *temporaryValueDelegationFix) Value(key interface{}) interface{} {
  47. return t.value.Value(key)
  48. }