-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackend_servers.go
69 lines (58 loc) · 1.59 KB
/
backend_servers.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
package loadbalancer
// Note: Some methods to start backend servers for testing during development
import (
"errors"
"log"
"net/http"
"strings"
)
type BackendServer struct {
Address string
ActiveConnections int
}
// Custom error
var (
ErrInvalidServerAddress = errors.New("invalid server address")
)
// startBackendServers starts the backend servers in separate goroutines
func (lb *LoadBalancer) startBackendServers() error {
if len(lb.Configuration.BackendServers) == 0 {
return ErrNoBackendServersConfigured
}
for _, server := range lb.Configuration.BackendServers {
serverParts := strings.Split(server.Address, ":")
if len(serverParts) != 3 {
log.Println("invalid server address: " + server.Address)
return ErrInvalidServerAddress
}
port := serverParts[2]
channel := make(chan bool, 1)
go startServer(":"+port, channel)
<-channel
log.Println("Backend server started on port", port)
close(channel)
}
return nil
}
// startServer starts a dummy backend server
func startServer(serverPort string, startSignal chan<- bool) error {
startSignal <- true
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Printf("Backend server %s received request", serverPort)
w.Write([]byte("Hello from backend server " + serverPort))
})
err := http.ListenAndServe(serverPort, handler)
if err != nil {
return err
}
return nil
}
func (bs *BackendServer) IncreaseActiveConnections() {
bs.ActiveConnections++
}
func (bs *BackendServer) DecreaseActiveConnections() {
bs.ActiveConnections--
if bs.ActiveConnections < 0 {
bs.ActiveConnections = 0
}
}