github.com/eagleql/xray-core@v1.4.4/core/context.go (about)

     1  package core
     2  
     3  import (
     4  	"context"
     5  )
     6  
     7  // XrayKey is the key type of Instance in Context, exported for test.
     8  type XrayKey int
     9  
    10  const xrayKey XrayKey = 1
    11  
    12  // FromContext returns an Instance from the given context, or nil if the context doesn't contain one.
    13  func FromContext(ctx context.Context) *Instance {
    14  	if s, ok := ctx.Value(xrayKey).(*Instance); ok {
    15  		return s
    16  	}
    17  	return nil
    18  }
    19  
    20  // MustFromContext returns an Instance from the given context, or panics if not present.
    21  func MustFromContext(ctx context.Context) *Instance {
    22  	x := FromContext(ctx)
    23  	if x == nil {
    24  		panic("X is not in context.")
    25  	}
    26  	return x
    27  }