-
Notifications
You must be signed in to change notification settings - Fork 18
/
proxy.go
55 lines (49 loc) · 1005 Bytes
/
proxy.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
package main
import (
"net"
"sync"
)
// Proxy connections from Listen to Backend.
type Proxy struct {
Listen string
Backend string
listener net.Listener
}
func (p *Proxy) Run() error {
var err error
if p.listener, err = net.Listen("tcp", p.Listen); err != nil {
return err
}
wg := &sync.WaitGroup{}
for {
if conn, err := p.listener.Accept(); err == nil {
wg.Add(1)
go func() {
defer wg.Done()
p.handle(conn)
}()
} else {
return nil
}
}
wg.Wait()
return nil
}
func (p *Proxy) Close() error {
return p.listener.Close()
}
func (p *Proxy) handle(upConn net.Conn) {
defer upConn.Close()
logger.Infof("accepted: %s", upConn.RemoteAddr())
downConn, err := net.Dial("tcp", p.Backend)
if err != nil {
logger.Errorf("unable to connect to %s: %s", p.Backend, err)
return
}
defer downConn.Close()
if err := Pipe(upConn, downConn); err != nil {
logger.Errorf("pipe failed: %s", err)
} else {
logger.Infof("disconnected: %s", upConn.RemoteAddr())
}
}