-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
62 lines (59 loc) · 1.54 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
package main
import (
"context"
"fmt"
"github.com/rimo10/load_balancer/backend"
"github.com/rimo10/load_balancer/lb"
"net/http"
"net/http/httputil"
"net/url"
"time"
"github.com/rimo10/load_balancer/serverpool"
"github.com/rimo10/load_balancer/utils"
"log"
)
func main() {
config, err := utils.GetLBConfig()
if err != nil {
log.Fatal(err)
}
sp, err := serverpool.NewServerPool()
print(sp)
if err != nil {
log.Fatalf(err.Error())
}
// ctx := context.Background()
loadbalancer := lb.NewLoadBalancer(sp)
for _, b := range config.Backends {
serverUrl, err := url.Parse(b.URL)
if err != nil {
log.Fatal(err)
}
proxy := httputil.NewSingleHostReverseProxy(serverUrl)
proxy.ErrorHandler = func(w http.ResponseWriter, r *http.Request, err error) {
log.Printf("[%s] %s \n", serverUrl.Host, err.Error())
retries := loadbalancer.GetRetryFromContext(r)
if retries < 3 {
select {
case <-time.After(10 * time.Millisecond):
ctx := context.WithValue(r.Context(), lb.Retry, retries+1)
proxy.ServeHTTP(w, r.WithContext(ctx))
}
return
}
sp.MarkBackendStatus(serverUrl, false)
}
newBackend := backend.NewBackend(serverUrl, proxy, b.Weight)
sp.AddBackend(newBackend)
log.Printf("Configured Server : %s\n", serverUrl)
}
server := http.Server{
Addr: fmt.Sprintf(":%d", config.Port),
Handler: http.HandlerFunc(loadbalancer.Serve),
}
go serverpool.LaunchHealthCheck(sp)
log.Printf("Load Balancer started at : %d\n", config.Port)
if err := server.ListenAndServe(); err != nil {
log.Fatal(err)
}
}