context.go 1.7 KB

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