-
Notifications
You must be signed in to change notification settings - Fork 0
/
loadbalancer.go
58 lines (49 loc) · 1.43 KB
/
loadbalancer.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
package loadbalancer
import (
"net/http"
"sync"
)
type LoadBalancer struct {
Configuration *AppConfig
NextServerIndex int
NextServer BackendServer
mutex sync.Mutex
}
func (lb *LoadBalancer) Start() error {
lb.mutex.Lock()
defer lb.mutex.Unlock()
if !lb.Configuration.InProduction && lb.Configuration.StartGivenServers {
lb.startBackendServers()
}
http.ListenAndServe(
lb.Configuration.LoadBalancerPort,
http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
lb.preProcess(lb.NextServerIndex)
r.Header.Add("Pass-Through-Host", lb.NextServer.Address)
processRequestFromBackend(w, r)
lb.postProcess(lb.NextServerIndex)
lb.decideNextServerIndex()
},
),
)
return nil
}
func (lb *LoadBalancer) decideNextServerIndex() {
switch lb.Configuration.SchedulingAlgorithm {
case AllowedSchedulingAlgorithms["round-robin"]:
lb.roundRobinDecider()
case AllowedSchedulingAlgorithms["least-connections"]:
lb.leastConnectionsDecider()
}
}
func (lb *LoadBalancer) preProcess(ServerIndex int) {
selectedServer := lb.Configuration.BackendServers[ServerIndex]
selectedServer.IncreaseActiveConnections()
lb.Configuration.BackendServers[ServerIndex] = selectedServer
}
func (lb *LoadBalancer) postProcess(ServerIndex int) {
selectedServer := lb.Configuration.BackendServers[ServerIndex]
selectedServer.DecreaseActiveConnections()
lb.Configuration.BackendServers[ServerIndex] = selectedServer
}