-
-
Notifications
You must be signed in to change notification settings - Fork 78
/
Copy pathlistener.go
65 lines (56 loc) · 1.29 KB
/
listener.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package grpc_proxy
import (
"net"
"sync"
"github.com/sirupsen/logrus"
)
type proxiedConn struct {
net.Conn
originalDest string
}
func (p proxiedConn) OriginalDestination() string {
return p.originalDest
}
// listens on a net.Listener as well as a channel for internal redirects
// while preserving original destination
type proxyListener struct {
logger logrus.FieldLogger
channel chan net.Conn
errs chan error
net.Listener
once sync.Once
}
func newProxyListener(logger logrus.FieldLogger, listener net.Listener) *proxyListener {
return &proxyListener{
logger: logger,
channel: make(chan net.Conn),
errs: make(chan error),
Listener: listener,
once: sync.Once{},
}
}
func (l *proxyListener) internalRedirect(conn net.Conn, originalDestination string) {
l.channel <- proxiedConn{conn, originalDestination}
}
func (l *proxyListener) Accept() (net.Conn, error) {
l.once.Do(func() {
// listen on the actual net.Listener and put into the channel
go func() {
for {
conn, err := l.Listener.Accept()
if err != nil {
l.errs <- err
continue
}
l.logger.Debugf("Got connection from address %v", conn.RemoteAddr())
l.channel <- conn
}
}()
})
select {
case conn := <-l.channel:
return conn, nil
case err := <-l.errs:
return nil, err
}
}