1
0

context.go 2.3 KB

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