-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathloadbalancer.go
More file actions
36 lines (31 loc) · 805 Bytes
/
loadbalancer.go
File metadata and controls
36 lines (31 loc) · 805 Bytes
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
package main
import (
"fmt"
"net/http"
)
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 (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 %q\n", targetServer.Address())
targetServer.Serve(rw, req)
}