context.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package session
  2. import "context"
  3. type sessionKey int
  4. const (
  5. idSessionKey sessionKey = iota
  6. inboundSessionKey
  7. outboundSessionKey
  8. contentSessionKey
  9. )
  10. // ContextWithID returns a new context with the given ID.
  11. func ContextWithID(ctx context.Context, id ID) context.Context {
  12. return context.WithValue(ctx, idSessionKey, id)
  13. }
  14. // IDFromContext returns ID in this context, or 0 if not contained.
  15. func IDFromContext(ctx context.Context) ID {
  16. if id, ok := ctx.Value(idSessionKey).(ID); ok {
  17. return id
  18. }
  19. return 0
  20. }
  21. func ContextWithInbound(ctx context.Context, inbound *Inbound) context.Context {
  22. return context.WithValue(ctx, inboundSessionKey, inbound)
  23. }
  24. func InboundFromContext(ctx context.Context) *Inbound {
  25. if inbound, ok := ctx.Value(inboundSessionKey).(*Inbound); ok {
  26. return inbound
  27. }
  28. return nil
  29. }
  30. func ContextWithOutbound(ctx context.Context, outbound *Outbound) context.Context {
  31. return context.WithValue(ctx, outboundSessionKey, outbound)
  32. }
  33. func OutboundFromContext(ctx context.Context) *Outbound {
  34. if outbound, ok := ctx.Value(outboundSessionKey).(*Outbound); ok {
  35. return outbound
  36. }
  37. return nil
  38. }
  39. func ContextWithContent(ctx context.Context, content *Content) context.Context {
  40. return context.WithValue(ctx, contentSessionKey, content)
  41. }
  42. func ContentFromContext(ctx context.Context) *Content {
  43. if content, ok := ctx.Value(contentSessionKey).(*Content); ok {
  44. return content
  45. }
  46. return nil
  47. }