proxy: TCPProxy connects to TCP but can read from other things

The TCPProxy can proxy from anything which satisfies this interface:

type Conn interface {
  	io.Reader
	io.Writer
	io.Closer
	CloseRead() error
	CloseWrite() error
}

Signed-off-by: David Scott <dave.scott@docker.com>
This commit is contained in:
David Scott 2016-04-14 15:12:07 +01:00
parent 90b1734a52
commit 2cf9295602

View File

@ -8,6 +8,14 @@ import (
"github.com/Sirupsen/logrus"
)
type Conn interface {
io.Reader
io.Writer
io.Closer
CloseRead() error
CloseWrite() error
}
// TCPProxy is a proxy for TCP connections. It implements the Proxy interface to
// handle TCP traffic forwarding between the frontend and backend addresses.
type TCPProxy struct {
@ -31,7 +39,7 @@ func NewTCPProxy(frontendAddr, backendAddr *net.TCPAddr) (*TCPProxy, error) {
}, nil
}
func (proxy *TCPProxy) clientLoop(client *net.TCPConn, quit chan bool) {
func (proxy *TCPProxy) clientLoop(client Conn, quit chan bool) {
backend, err := net.DialTCP("tcp", nil, proxy.backendAddr)
if err != nil {
logrus.Printf("Can't forward traffic to backend tcp/%v: %s\n", proxy.backendAddr, err)
@ -40,7 +48,7 @@ func (proxy *TCPProxy) clientLoop(client *net.TCPConn, quit chan bool) {
}
event := make(chan int64)
var broker = func(to, from *net.TCPConn) {
var broker = func(to, from Conn) {
written, err := io.Copy(to, from)
if err != nil {
// If the socket we are writing to is shutdown with
@ -85,7 +93,7 @@ func (proxy *TCPProxy) Run() {
logrus.Printf("Stopping proxy on tcp/%v for tcp/%v (%s)", proxy.frontendAddr, proxy.backendAddr, err)
return
}
go proxy.clientLoop(client.(*net.TCPConn), quit)
go proxy.clientLoop(client.(Conn), quit)
}
}