-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
97 lines (75 loc) · 2.01 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
88
89
90
91
92
93
94
95
96
97
package main
import (
"fmt"
"net/http"
"sync"
"time"
)
var (
// Need a mutex when updating the
// lastForwardIndex variable
mutex sync.Mutex
lastForwardedIndex = 0
totalBackends = 4
serverListFirst = []*server{
newServer("Server-1", "http://localhost:8000"),
newServer("Server-2", "http://localhost:8001"),
newServer("Server-3", "http://localhost:8002"),
newServer("Server-4", "http://localhost:8003"),
}
serverListSecond = []*server{
newServer("Server-4", "http://localhost:8004"),
newServer("Server-5", "http://localhost:8005"),
newServer("Server-6", "http://localhost:8006"),
newServer("Server-7", "http://localhost:8007"),
}
)
func main() {
http.HandleFunc("/", handleRequest)
go startHealthCheck(300)
http.ListenAndServe(":8000", nil)
}
func handleRequest(res http.ResponseWriter, req *http.Request) {
// Find the alive server
server, err := getAliveServer()
// If there's not alive servers
// send a response
if err != nil {
http.Error(res, "Request cannot be handled. Reason: "+err.Error(), http.StatusServiceUnavailable)
return
}
req.Host = server.URL
server.ReverseProxy.ServeHTTP(res, req)
}
func getBackend() *server {
// This is a problem for my usecase
// I need to use different servers
// dependant on the current date
// First half of the month i will be
// using serverListFirst
// second half of the month i will be
// using serverListSecond
currentTime := time.Now()
if currentTime.Day() < 15 {
backend := serverListFirst[lastForwardedIndex]
mutex.Lock()
lastForwardedIndex = (lastForwardedIndex + 1) % totalBackends
mutex.Unlock()
return backend
}
backend := serverListSecond[lastForwardedIndex]
mutex.Lock()
lastForwardedIndex = (lastForwardedIndex + 1) % totalBackends
mutex.Unlock()
return backend
}
func getAliveServer() (*server, error) {
// n servers <==> loop n times
for i := 0; i < totalBackends; i++ {
server := getBackend()
if server.Alive {
return server, nil
}
}
return nil, fmt.Errorf("all servers are dead")
}