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