-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
87 lines (76 loc) · 1.96 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
package main
import (
"fmt"
"net/http"
"net/http/httputil"
"net/url"
"os"
)
type Server interface {
Address() string
IsAlive() bool
Serve(rw http.ResponseWriter, r *http.Request)
}
type simpleServer struct {
addr string
proxy *httputil.ReverseProxy
}
func newSimpleServer(addr string) *simpleServer {
serverUrl, err := url.Parse(addr)
handleErr(err)
return &simpleServer{
addr: addr,
proxy: httputil.NewSingleHostReverseProxy(serverUrl),
}
}
type LoadBalancer struct {
port string
roundRobinCount int
servers []Server
}
func NewLoadBalancer(port string, servers []Server) *LoadBalancer {
return &LoadBalancer{
port: port,
roundRobinCount: 0,
servers: servers,
}
}
func handleErr(err error) {
if err != nil {
fmt.Printf("error: %v\n", err)
os.Exit(1)
}
}
func (s *simpleServer) Address() string { return s.addr }
func (s *simpleServer) IsAlive() bool { return true }
func (s *simpleServer) Serve(rw http.ResponseWriter, req *http.Request) {
s.proxy.ServeHTTP(rw, req)
}
func (lb *LoadBalancer) getNextAvailableServer() Server {
server := lb.servers[lb.roundRobinCount%len(lb.servers)]
for !server.IsAlive() {
lb.roundRobinCount++
server = lb.servers[lb.roundRobinCount%len(lb.servers)]
}
lb.roundRobinCount++
return server
}
func (lb *LoadBalancer) serveProxy(rw http.ResponseWriter, req *http.Request) {
targetServer := lb.getNextAvailableServer()
fmt.Printf("forwarding request to address %q\n", targetServer.Address())
targetServer.Serve(rw, req)
}
func main() {
servers := []Server{
newSimpleServer("https://www.facebook.com"),
newSimpleServer("http://www.bing.com"),
newSimpleServer("https://www.duckduckgo.com"),
}
lb := NewLoadBalancer("8000", servers)
handleRedirect := func(rw http.ResponseWriter, req *http.Request) {
lb.serveProxy(rw, req)
}
http.HandleFunc("/", handleRedirect)
fmt.Printf("Serving requests at localhost: %s\n", lb.port)
http.ListenAndServe(":"+lb.port, nil)
}