context.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. package internet
  2. import (
  3. "context"
  4. "v2ray.com/core/common/net"
  5. )
  6. type key int
  7. const (
  8. streamSettingsKey key = iota
  9. dialerSrcKey
  10. bindAddrKey
  11. )
  12. func ContextWithStreamSettings(ctx context.Context, streamSettings *MemoryStreamConfig) context.Context {
  13. return context.WithValue(ctx, streamSettingsKey, streamSettings)
  14. }
  15. func StreamSettingsFromContext(ctx context.Context) *MemoryStreamConfig {
  16. ss := ctx.Value(streamSettingsKey)
  17. if ss == nil {
  18. return nil
  19. }
  20. return ss.(*MemoryStreamConfig)
  21. }
  22. func ContextWithDialerSource(ctx context.Context, addr net.Address) context.Context {
  23. return context.WithValue(ctx, dialerSrcKey, addr)
  24. }
  25. func DialerSourceFromContext(ctx context.Context) net.Address {
  26. if addr, ok := ctx.Value(dialerSrcKey).(net.Address); ok {
  27. return addr
  28. }
  29. return net.AnyIP
  30. }
  31. func ContextWithBindAddress(ctx context.Context, dest net.Destination) context.Context {
  32. return context.WithValue(ctx, bindAddrKey, dest)
  33. }
  34. func BindAddressFromContext(ctx context.Context) net.Destination {
  35. if addr, ok := ctx.Value(bindAddrKey).(net.Destination); ok {
  36. return addr
  37. }
  38. return net.Destination{}
  39. }