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