proxy.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. // Package proxy provides a network Proxy interface and implementations for TCP
  2. // and UDP.
  3. package proxy
  4. import (
  5. "fmt"
  6. "net"
  7. )
  8. // Proxy defines the behavior of a proxy. It forwards traffic back and forth
  9. // between two endpoints : the frontend and the backend.
  10. // It can be used to do software port-mapping between two addresses.
  11. // e.g. forward all traffic between the frontend (host) 127.0.0.1:3000
  12. // to the backend (container) at 172.17.42.108:4000.
  13. type Proxy interface {
  14. // Run starts forwarding traffic back and forth between the front
  15. // and back-end addresses.
  16. Run()
  17. // Close stops forwarding traffic and close both ends of the Proxy.
  18. Close()
  19. // FrontendAddr returns the address on which the proxy is listening.
  20. FrontendAddr() net.Addr
  21. // BackendAddr returns the proxied address.
  22. BackendAddr() net.Addr
  23. }
  24. // NewProxy creates a Proxy according to the specified frontendAddr and backendAddr.
  25. func NewProxy(frontendAddr, backendAddr net.Addr) (Proxy, error) {
  26. switch frontendAddr.(type) {
  27. case *net.UDPAddr:
  28. return NewUDPProxy(frontendAddr.(*net.UDPAddr), backendAddr.(*net.UDPAddr))
  29. case *net.TCPAddr:
  30. return NewTCPProxy(frontendAddr.(*net.TCPAddr), backendAddr.(*net.TCPAddr))
  31. default:
  32. panic(fmt.Errorf("Unsupported protocol"))
  33. }
  34. }