context.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. targetKey
  10. originalTargetKey
  11. inboundEntryPointKey
  12. inboundTagKey
  13. resolvedIPsKey
  14. )
  15. // ContextWithSource creates a new context with given source.
  16. func ContextWithSource(ctx context.Context, src net.Destination) context.Context {
  17. return context.WithValue(ctx, sourceKey, src)
  18. }
  19. // SourceFromContext retreives source from the given context.
  20. func SourceFromContext(ctx context.Context) (net.Destination, bool) {
  21. v, ok := ctx.Value(sourceKey).(net.Destination)
  22. return v, ok
  23. }
  24. func ContextWithOriginalTarget(ctx context.Context, dest net.Destination) context.Context {
  25. return context.WithValue(ctx, originalTargetKey, dest)
  26. }
  27. func OriginalTargetFromContext(ctx context.Context) (net.Destination, bool) {
  28. v, ok := ctx.Value(originalTargetKey).(net.Destination)
  29. return v, ok
  30. }
  31. func ContextWithTarget(ctx context.Context, dest net.Destination) context.Context {
  32. return context.WithValue(ctx, targetKey, dest)
  33. }
  34. func TargetFromContext(ctx context.Context) (net.Destination, bool) {
  35. v, ok := ctx.Value(targetKey).(net.Destination)
  36. return v, ok
  37. }
  38. func ContextWithInboundEntryPoint(ctx context.Context, dest net.Destination) context.Context {
  39. return context.WithValue(ctx, inboundEntryPointKey, dest)
  40. }
  41. func InboundEntryPointFromContext(ctx context.Context) (net.Destination, bool) {
  42. v, ok := ctx.Value(inboundEntryPointKey).(net.Destination)
  43. return v, ok
  44. }
  45. func ContextWithInboundTag(ctx context.Context, tag string) context.Context {
  46. return context.WithValue(ctx, inboundTagKey, tag)
  47. }
  48. func InboundTagFromContext(ctx context.Context) (string, bool) {
  49. v, ok := ctx.Value(inboundTagKey).(string)
  50. return v, ok
  51. }
  52. func ContextWithResolveIPs(ctx context.Context, ips []net.Address) context.Context {
  53. return context.WithValue(ctx, resolvedIPsKey, ips)
  54. }
  55. func ResolvedIPsFromContext(ctx context.Context) ([]net.Address, bool) {
  56. ips, ok := ctx.Value(resolvedIPsKey).([]net.Address)
  57. return ips, ok
  58. }