-
Notifications
You must be signed in to change notification settings - Fork 0
/
proxy.go
80 lines (65 loc) · 1.6 KB
/
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
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
package main
import (
"flag"
"io"
"log"
"net"
"strings"
)
type Backends struct {
servers []string
n int
}
func (b *Backends) Choose() string {
idx := b.n % len(b.servers)
b.n++
return b.servers[idx]
}
func (b *Backends) String() string {
return strings.Join(b.servers, ", ")
}
var (
bind = flag.String("bind", "", "The address to bind on")
balance = flag.String("balance", "", "The backend servers to balance connections across, separated by commas")
backends *Backends
)
func init() {
flag.Parse()
if *bind == "" {
log.Fatalln("specify the address to listen on with -bind")
}
servers := strings.Split(*balance, ",")
if len(servers) == 1 && servers[0] == "" {
log.Fatalln("please specify backend servers with -backends")
}
backends = &Backends{servers: servers}
}
func copy(wc io.WriteCloser, r io.Reader) {
defer wc.Close()
io.Copy(wc, r)
}
func handleConnection(us net.Conn, server string) {
ds, err := net.Dial("tcp", server)
if err != nil {
us.Close()
log.Printf("failed to dial %s: %s", server, err)
return
}
go copy(ds, us)
go copy(us, ds)
}
func main() {
ln, err := net.Listen("tcp", *bind)
if err != nil {
log.Fatalf("failed to bind: %s", err)
}
log.Printf("listening on %s, balancing %s", *bind, backends)
for {
conn, err := ln.Accept()
if err != nil {
log.Printf("failed to accept: %s", err)
continue
}
go handleConnection(conn, backends.Choose())
}
}