github.com/v2fly/v2ray-core/v4@v4.45.2/context.go (about) 1 //go:build !confonly 2 // +build !confonly 3 4 package core 5 6 import ( 7 "context" 8 ) 9 10 // V2rayKey is the key type of Instance in Context, exported for test. 11 type v2rayKeyType int 12 13 const v2rayKey v2rayKeyType = 1 14 15 // FromContext returns an Instance from the given context, or nil if the context doesn't contain one. 16 func FromContext(ctx context.Context) *Instance { 17 if s, ok := ctx.Value(v2rayKey).(*Instance); ok { 18 return s 19 } 20 return nil 21 } 22 23 // MustFromContext returns an Instance from the given context, or panics if not present. 24 func MustFromContext(ctx context.Context) *Instance { 25 v := FromContext(ctx) 26 if v == nil { 27 panic("V is not in context.") 28 } 29 return v 30 } 31 32 /* toContext returns ctx from the given context, or creates an Instance if the context doesn't find that. 33 34 It is unsupported to use this function to create a context that is suitable to invoke V2Ray's internal component 35 in third party code, you shouldn't use //go:linkname to alias of this function into your own package and 36 use this function in your third party code. 37 38 For third party code, usage enabled by creating a context to interact with V2Ray's internal component is unsupported, 39 and may break at any time. 40 41 */ 42 func toContext(ctx context.Context, v *Instance) context.Context { 43 if FromContext(ctx) != v { 44 ctx = context.WithValue(ctx, v2rayKey, v) 45 } 46 return ctx 47 } 48 49 /*ToBackgroundDetachedContext create a detached context from another context 50 Internal API 51 */ 52 func ToBackgroundDetachedContext(ctx context.Context) context.Context { 53 return &temporaryValueDelegationFix{context.Background(), ctx} 54 } 55 56 type temporaryValueDelegationFix struct { 57 context.Context 58 value context.Context 59 } 60 61 func (t *temporaryValueDelegationFix) Value(key interface{}) interface{} { 62 return t.value.Value(key) 63 }