context.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. )
  11. // ContextWithID returns a new context with the given ID.
  12. func ContextWithID(ctx context.Context, id ID) context.Context {
  13. return context.WithValue(ctx, idSessionKey, id)
  14. }
  15. // IDFromContext returns ID in this context, or 0 if not contained.
  16. func IDFromContext(ctx context.Context) ID {
  17. if id, ok := ctx.Value(idSessionKey).(ID); ok {
  18. return id
  19. }
  20. return 0
  21. }
  22. func ContextWithInbound(ctx context.Context, inbound *Inbound) context.Context {
  23. return context.WithValue(ctx, inboundSessionKey, inbound)
  24. }
  25. func InboundFromContext(ctx context.Context) *Inbound {
  26. if inbound, ok := ctx.Value(inboundSessionKey).(*Inbound); ok {
  27. return inbound
  28. }
  29. return nil
  30. }
  31. func ContextWithOutbound(ctx context.Context, outbound *Outbound) context.Context {
  32. return context.WithValue(ctx, outboundSessionKey, outbound)
  33. }
  34. func OutboundFromContext(ctx context.Context) *Outbound {
  35. if outbound, ok := ctx.Value(outboundSessionKey).(*Outbound); ok {
  36. return outbound
  37. }
  38. return nil
  39. }
  40. func ContextWithContent(ctx context.Context, content *Content) context.Context {
  41. return context.WithValue(ctx, contentSessionKey, content)
  42. }
  43. func ContentFromContext(ctx context.Context) *Content {
  44. if content, ok := ctx.Value(contentSessionKey).(*Content); ok {
  45. return content
  46. }
  47. return nil
  48. }
  49. // ContextWithMuxPrefered returns a new context with the given bool
  50. func ContextWithMuxPrefered(ctx context.Context, forced bool) context.Context {
  51. return context.WithValue(ctx, muxPreferedSessionKey, forced)
  52. }
  53. // MuxPreferedFromContext returns value in this context, or false if not contained.
  54. func MuxPreferedFromContext(ctx context.Context) bool {
  55. if val, ok := ctx.Value(muxPreferedSessionKey).(bool); ok {
  56. return val
  57. }
  58. return false
  59. }