1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-07-20 12:14:15 -04:00
v2fly/context.go

62 lines
1.7 KiB
Go
Raw Normal View History

package core
import (
"context"
)
2020-06-27 00:28:53 -04:00
// V2rayKey is the key type of Instance in Context, exported for test.
2021-05-04 09:19:23 -04:00
type v2rayKeyType int
2021-05-04 09:19:23 -04:00
const v2rayKey v2rayKeyType = 1
2018-02-21 11:05:29 -05:00
// FromContext returns an Instance from the given context, or nil if the context doesn't contain one.
func FromContext(ctx context.Context) *Instance {
if s, ok := ctx.Value(v2rayKey).(*Instance); ok {
return s
}
return nil
}
2018-02-21 11:05:29 -05:00
// MustFromContext returns an Instance from the given context, or panics if not present.
func MustFromContext(ctx context.Context) *Instance {
v := FromContext(ctx)
if v == nil {
panic("V is not in context.")
}
return v
}
2022-06-28 08:26:01 -04:00
/*
toContext returns ctx from the given context, or creates an Instance if the context doesn't find that.
2021-04-05 13:13:24 -04:00
It is unsupported to use this function to create a context that is suitable to invoke V2Ray's internal component
in third party code, you shouldn't use //go:linkname to alias of this function into your own package and
use this function in your third party code.
For third party code, usage enabled by creating a context to interact with V2Ray's internal component is unsupported,
and may break at any time.
*/
func toContext(ctx context.Context, v *Instance) context.Context {
if FromContext(ctx) != v {
ctx = context.WithValue(ctx, v2rayKey, v)
}
return ctx
}
2022-06-28 08:26:01 -04:00
/*
ToBackgroundDetachedContext create a detached context from another context
2021-05-04 16:06:23 -04:00
Internal API
*/
func ToBackgroundDetachedContext(ctx context.Context) context.Context {
return &temporaryValueDelegationFix{context.Background(), ctx}
}
type temporaryValueDelegationFix struct {
context.Context
value context.Context
}
func (t *temporaryValueDelegationFix) Value(key interface{}) interface{} {
return t.value.Value(key)
}