context.go 637 B

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