v2ray-core/common/session/context.go

73 lines
1.9 KiB
Go
Raw Normal View History

package session
import "context"
type sessionKey int
const (
idSessionKey sessionKey = iota
inboundSessionKey
outboundSessionKey
2019-02-22 15:58:16 +00:00
contentSessionKey
2019-11-26 05:30:44 +00:00
muxPreferedSessionKey
)
// ContextWithID returns a new context with the given ID.
func ContextWithID(ctx context.Context, id ID) context.Context {
return context.WithValue(ctx, idSessionKey, id)
}
// IDFromContext returns ID in this context, or 0 if not contained.
func IDFromContext(ctx context.Context) ID {
if id, ok := ctx.Value(idSessionKey).(ID); ok {
return id
}
return 0
}
func ContextWithInbound(ctx context.Context, inbound *Inbound) context.Context {
return context.WithValue(ctx, inboundSessionKey, inbound)
}
func InboundFromContext(ctx context.Context) *Inbound {
if inbound, ok := ctx.Value(inboundSessionKey).(*Inbound); ok {
return inbound
}
return nil
}
func ContextWithOutbound(ctx context.Context, outbound *Outbound) context.Context {
return context.WithValue(ctx, outboundSessionKey, outbound)
}
func OutboundFromContext(ctx context.Context) *Outbound {
if outbound, ok := ctx.Value(outboundSessionKey).(*Outbound); ok {
return outbound
}
return nil
}
2019-02-22 15:58:16 +00:00
func ContextWithContent(ctx context.Context, content *Content) context.Context {
return context.WithValue(ctx, contentSessionKey, content)
}
func ContentFromContext(ctx context.Context) *Content {
if content, ok := ctx.Value(contentSessionKey).(*Content); ok {
return content
}
return nil
}
2019-06-29 15:43:30 +00:00
// ContextWithMuxPrefered returns a new context with the given bool
func ContextWithMuxPrefered(ctx context.Context, forced bool) context.Context {
2019-11-26 05:30:44 +00:00
return context.WithValue(ctx, muxPreferedSessionKey, forced)
2019-06-29 15:43:30 +00:00
}
// MuxPreferedFromContext returns value in this context, or false if not contained.
func MuxPreferedFromContext(ctx context.Context) bool {
2019-11-26 05:30:44 +00:00
if val, ok := ctx.Value(muxPreferedSessionKey).(bool); ok {
2019-06-29 15:43:30 +00:00
return val
}
return false
}