context.go 1.1 KB

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