context.go 611 B

123456789101112131415161718192021222324252627
  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. }