context.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package proxy
  2. import (
  3. "context"
  4. "v2ray.com/core/common/net"
  5. )
  6. type key int
  7. const (
  8. sourceKey key = iota
  9. destinationKey
  10. originalDestinationKey
  11. inboundDestinationKey
  12. inboundTagKey
  13. resolvedIPsKey
  14. )
  15. func ContextWithSource(ctx context.Context, src net.Destination) context.Context {
  16. return context.WithValue(ctx, sourceKey, src)
  17. }
  18. func SourceFromContext(ctx context.Context) net.Destination {
  19. v := ctx.Value(sourceKey)
  20. if v == nil {
  21. return net.Destination{}
  22. }
  23. return v.(net.Destination)
  24. }
  25. func ContextWithOriginalDestination(ctx context.Context, dest net.Destination) context.Context {
  26. return context.WithValue(ctx, originalDestinationKey, dest)
  27. }
  28. func OriginalDestinationFromContext(ctx context.Context) net.Destination {
  29. v := ctx.Value(originalDestinationKey)
  30. if v == nil {
  31. return net.Destination{}
  32. }
  33. return v.(net.Destination)
  34. }
  35. func ContextWithDestination(ctx context.Context, dest net.Destination) context.Context {
  36. return context.WithValue(ctx, destinationKey, dest)
  37. }
  38. func DestinationFromContext(ctx context.Context) net.Destination {
  39. v := ctx.Value(destinationKey)
  40. if v == nil {
  41. return net.Destination{}
  42. }
  43. return v.(net.Destination)
  44. }
  45. func ContextWithInboundDestination(ctx context.Context, dest net.Destination) context.Context {
  46. return context.WithValue(ctx, inboundDestinationKey, dest)
  47. }
  48. func InboundDestinationFromContext(ctx context.Context) net.Destination {
  49. v := ctx.Value(inboundDestinationKey)
  50. if v == nil {
  51. return net.Destination{}
  52. }
  53. return v.(net.Destination)
  54. }
  55. func ContextWithInboundTag(ctx context.Context, tag string) context.Context {
  56. return context.WithValue(ctx, inboundTagKey, tag)
  57. }
  58. func InboundTagFromContext(ctx context.Context) string {
  59. v := ctx.Value(inboundTagKey)
  60. if v == nil {
  61. return ""
  62. }
  63. return v.(string)
  64. }
  65. func ContextWithResolveIPs(ctx context.Context, ips []net.Address) context.Context {
  66. return context.WithValue(ctx, resolvedIPsKey, ips)
  67. }
  68. func ResolvedIPsFromContext(ctx context.Context) ([]net.Address, bool) {
  69. ips, ok := ctx.Value(resolvedIPsKey).([]net.Address)
  70. return ips, ok
  71. }