context.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package core
  2. import (
  3. "context"
  4. )
  5. // XrayKey is the key type of Instance in Context, exported for test.
  6. type XrayKey int
  7. const xrayKey XrayKey = 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(xrayKey).(*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. x := FromContext(ctx)
  18. if x == nil {
  19. panic("X is not in context.")
  20. }
  21. return x
  22. }
  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 Xray'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 Xray'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, xrayKey, v)
  34. }
  35. return ctx
  36. }
  37. /*
  38. ToBackgroundDetachedContext create a detached context from another context
  39. Internal API
  40. */
  41. func ToBackgroundDetachedContext(ctx context.Context) context.Context {
  42. instance := MustFromContext(ctx)
  43. return toContext(context.Background(), instance)
  44. }