commit f692dc7ce3796dc94b6ffd6a242f50740eed7398 Author: dingjun Date: Sat Apr 13 16:56:46 2019 +0800 Initial commit diff --git a/README.md b/README.md new file mode 100644 index 0000000..0ecec86 --- /dev/null +++ b/README.md @@ -0,0 +1,4 @@ +protolistener +===== + +wrap github.com/pires/go-proxyproto to net.Listener \ No newline at end of file diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..164d16b --- /dev/null +++ b/go.mod @@ -0,0 +1,5 @@ +module github.com/fangdingjun/proto_listener + +go 1.13 + +require github.com/pires/go-proxyproto v0.0.0-20190111085350-4d51b51e3bfc diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..df4f4b9 --- /dev/null +++ b/go.sum @@ -0,0 +1,2 @@ +github.com/pires/go-proxyproto v0.0.0-20190111085350-4d51b51e3bfc h1:lNOt1SMsgHXTdpuGw+RpnJtzUcCb/oRKZP65pBy9pr8= +github.com/pires/go-proxyproto v0.0.0-20190111085350-4d51b51e3bfc/go.mod h1:6/gX3+E/IYGa0wMORlSMla999awQFdbaeQCHjSMKIzY= diff --git a/proxy_protocol.go b/proxy_protocol.go new file mode 100644 index 0000000..9c1b2b6 --- /dev/null +++ b/proxy_protocol.go @@ -0,0 +1,50 @@ +package protolistener + +import ( + "bufio" + "net" + + proxyproto "github.com/pires/go-proxyproto" +) + +type protoListener struct { + net.Listener +} + +type protoConn struct { + net.Conn + headerDone bool + r *bufio.Reader + proxy *proxyproto.Header +} + +func (l *protoListener) Accept() (net.Conn, error) { + c, err := l.Listener.Accept() + if err != nil { + return nil, err + } + return &protoConn{Conn: c}, err +} + +func (c *protoConn) Read(buf []byte) (int, error) { + var err error + if !c.headerDone { + c.r = bufio.NewReader(c.Conn) + c.proxy, err = proxyproto.Read(c.r) + if err != nil && err != proxyproto.ErrNoProxyProtocol { + return 0, err + } + c.headerDone = true + return c.r.Read(buf) + } + return c.r.Read(buf) +} + +func (c *protoConn) RemoteAddr() net.Addr { + if c.proxy == nil { + return c.Conn.RemoteAddr() + } + return &net.TCPAddr{ + IP: c.proxy.SourceAddress, + Port: int(c.proxy.SourcePort)} +}