-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
72 lines (61 loc) · 1.33 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
package main
import (
"log"
"net/http"
"net/http/httputil"
"net/url"
"simple-load-balancer/backend"
"simple-load-balancer/server"
"time"
)
const (
Attempts int = iota // implement constants incremetally
Retry
)
func main() {
backendURLs := []*url.URL{
parseURL("http://localhost:8080"),
parseURL("http://localhost:8081"),
parseURL("http://localhost:8082"),
}
backends := make([]*backend.Backend, len(backendURLs))
for i, backendURL := range backendURLs {
backends[i] = &backend.Backend{
URL: backendURL,
Alive: true,
ReverseProxy: httputil.NewSingleHostReverseProxy(backendURL),
}
}
var server server.ServerPool = server.ServerPool{
Backends: backends,
Current: 0,
}
go healthCheck(&server)
}
func healthCheck(s *server.ServerPool) {
t := time.NewTicker(time.Second * 20)
for {
select {
case <-t.C:
log.Println("Starting health check...")
s.HealthCheck()
log.Println("Health check completed")
}
}
}
func parseURL(urlstring string) *url.URL {
parsedURL, _ := url.Parse(urlstring)
return parsedURL
}
func GetRetryFromContext(r *http.Request) int {
if retry, ok := r.Context().Value(Retry).(int); ok {
return retry
}
return 0
}
func GetAttemptFromContext(r *http.Request) int {
if attempt, ok := r.Context().Value(Attempts).(int); ok {
return attempt
}
return 0
}