-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.go
94 lines (84 loc) · 1.48 KB
/
main.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package main
import (
"io"
"log"
"net"
"sync"
)
func main() {
proxy := NewProxy("127.0.0.1:8000", "redis:6379")
proxy.Start()
}
type Proxy struct {
from string
to string
done chan struct{}
}
func NewProxy(from, to string) *Proxy {
return &Proxy{
from: from,
to: to,
done: make(chan struct{}),
}
}
func (p *Proxy) Start() error {
log.Println("Starting proxy")
listener, err := net.Listen("tcp", p.from)
if err != nil {
return err
}
p.run(listener)
return nil
}
func (p *Proxy) Stop() {
log.Println("Stopping proxy")
if p.done == nil {
return
}
close(p.done)
p.done = nil
}
func (p *Proxy) run(listener net.Listener) {
for {
select {
case <-p.done:
return
default:
connection, err := listener.Accept()
if err == nil {
go p.handle(connection)
} else {
log.Println("Error accepting conn")
}
}
}
}
func (p *Proxy) handle(connection net.Conn) {
log.Println("Handling", connection)
defer log.Println("Done handling", connection)
defer connection.Close()
remote, err := net.Dial("tcp", p.to)
if err != nil {
log.Println("Error dialing remote host")
return
}
defer remote.Close()
wg := &sync.WaitGroup{}
wg.Add(2)
go p.copy(remote, connection, wg)
go p.copy(connection, remote, wg)
wg.Wait()
}
func (p *Proxy) copy(from, to net.Conn, wg *sync.WaitGroup) {
defer wg.Done()
select {
case <-p.done:
return
default:
if _, err := io.Copy(to, from); err != nil {
log.Println("Error from copy")
p.Stop()
return
}
}
}