context.go 769 B

12345678910111213141516171819202122232425262728293031323334
  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. func WithContext(ctx context.Context, v *Instance) context.Context {
  24. if FromContext(ctx) != v {
  25. ctx = context.WithValue(ctx, xrayKey, v)
  26. }
  27. return ctx
  28. }