github.com/xraypb/Xray-core@v1.8.1/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  }
    28  
    29  /*
    30  	toContext returns ctx from the given context, or creates an Instance if the context doesn't find that.
    31  
    32  It is unsupported to use this function to create a context that is suitable to invoke Xray's internal component
    33  in third party code, you shouldn't use //go:linkname to alias of this function into your own package and
    34  use this function in your third party code.
    35  
    36  For third party code, usage enabled by creating a context to interact with Xray's internal component is unsupported,
    37  and may break at any time.
    38  */
    39  func toContext(ctx context.Context, v *Instance) context.Context {
    40  	if FromContext(ctx) != v {
    41  		ctx = context.WithValue(ctx, xrayKey, v)
    42  	}
    43  	return ctx
    44  }
    45  
    46  /*
    47  ToBackgroundDetachedContext create a detached context from another context
    48  Internal API
    49  */
    50  func ToBackgroundDetachedContext(ctx context.Context) context.Context {
    51  	instance := MustFromContext(ctx)
    52  	return toContext(context.Background(), instance)
    53  }