context.go 632 B

1234567891011121314151617181920212223242526272829
  1. // +build !confonly
  2. package core
  3. import (
  4. "context"
  5. )
  6. // XrayKey is the key type of Instance in Context, exported for test.
  7. type XrayKey int
  8. const xrayKey XrayKey = 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(xrayKey).(*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. x := FromContext(ctx)
  19. if x == nil {
  20. panic("X is not in context.")
  21. }
  22. return x
  23. }