-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlbHandler.go
43 lines (34 loc) · 897 Bytes
/
lbHandler.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
package mybalancer
import (
"log"
"net/http"
"net/http/httputil"
"net/url"
"sync"
)
func lbHandlerGenerate(cfg Config) func(w http.ResponseWriter, r *http.Request) {
var mu sync.Mutex
var idx int = 0
// lbHandler is the handler for loadbalancing
lbHandler := func(w http.ResponseWriter, r *http.Request) {
maxLen := len(cfg.Backends)
// Round Robin
mu.Lock()
//getting current backend and if its dead we move to next idx
//-This is an Active check for the backend - we do this for every request
currentBackend := &cfg.Backends[idx%maxLen]
if currentBackend.GetIsDead() {
idx++
}
//choosing next backend server
targetURL, err := url.Parse(cfg.Backends[idx%maxLen].URL)
if err != nil {
log.Fatal(err.Error())
}
idx++
mu.Unlock()
reverseProxy := httputil.NewSingleHostReverseProxy(targetURL)
reverseProxy.ServeHTTP(w, r)
}
return lbHandler
}