github.com/eagleql/xray-core@v1.4.4/common/session/context.go (about) 1 package session 2 3 import "context" 4 5 type sessionKey int 6 7 const ( 8 idSessionKey sessionKey = iota 9 inboundSessionKey 10 outboundSessionKey 11 contentSessionKey 12 muxPreferedSessionKey 13 sockoptSessionKey 14 ) 15 16 // ContextWithID returns a new context with the given ID. 17 func ContextWithID(ctx context.Context, id ID) context.Context { 18 return context.WithValue(ctx, idSessionKey, id) 19 } 20 21 // IDFromContext returns ID in this context, or 0 if not contained. 22 func IDFromContext(ctx context.Context) ID { 23 if id, ok := ctx.Value(idSessionKey).(ID); ok { 24 return id 25 } 26 return 0 27 } 28 29 func ContextWithInbound(ctx context.Context, inbound *Inbound) context.Context { 30 return context.WithValue(ctx, inboundSessionKey, inbound) 31 } 32 33 func InboundFromContext(ctx context.Context) *Inbound { 34 if inbound, ok := ctx.Value(inboundSessionKey).(*Inbound); ok { 35 return inbound 36 } 37 return nil 38 } 39 40 func ContextWithOutbound(ctx context.Context, outbound *Outbound) context.Context { 41 return context.WithValue(ctx, outboundSessionKey, outbound) 42 } 43 44 func OutboundFromContext(ctx context.Context) *Outbound { 45 if outbound, ok := ctx.Value(outboundSessionKey).(*Outbound); ok { 46 return outbound 47 } 48 return nil 49 } 50 51 func ContextWithContent(ctx context.Context, content *Content) context.Context { 52 return context.WithValue(ctx, contentSessionKey, content) 53 } 54 55 func ContentFromContext(ctx context.Context) *Content { 56 if content, ok := ctx.Value(contentSessionKey).(*Content); ok { 57 return content 58 } 59 return nil 60 } 61 62 // ContextWithMuxPrefered returns a new context with the given bool 63 func ContextWithMuxPrefered(ctx context.Context, forced bool) context.Context { 64 return context.WithValue(ctx, muxPreferedSessionKey, forced) 65 } 66 67 // MuxPreferedFromContext returns value in this context, or false if not contained. 68 func MuxPreferedFromContext(ctx context.Context) bool { 69 if val, ok := ctx.Value(muxPreferedSessionKey).(bool); ok { 70 return val 71 } 72 return false 73 } 74 75 // ContextWithSockopt returns a new context with Socket configs included 76 func ContextWithSockopt(ctx context.Context, s *Sockopt) context.Context { 77 return context.WithValue(ctx, sockoptSessionKey, s) 78 } 79 80 // SockoptFromContext returns Socket configs in this context, or nil if not contained. 81 func SockoptFromContext(ctx context.Context) *Sockopt { 82 if sockopt, ok := ctx.Value(sockoptSessionKey).(*Sockopt); ok { 83 return sockopt 84 } 85 return nil 86 }