-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
109 lines (93 loc) · 2.56 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
98
99
100
101
102
103
104
105
106
107
108
109
package main
import (
"encoding/json"
"io/ioutil"
"log"
"net/http"
"net/http/httputil"
"net/url"
"sync"
"time"
)
type Server struct {
URL *url.URL // URL of the backend server.
ActiveConnections int // Count of active connections
Mutex sync.Mutex // A mutex for safe concurrency
Healthy bool
}
type Config struct {
HealthCheckInterval string `json:"healthCheckInterval"`
Servers []string `json:"servers"`
ListenPort string `json:"listenPort"`
}
func loadConfig(file string) (Config, error) {
var config Config
bytes, err := ioutil.ReadFile(file)
if err != nil {
return config, err
}
err = json.Unmarshal(bytes, &config)
if err != nil {
return config, err
}
return config, nil
}
func nextServerLeastActive(servers []*Server) *Server {
leastActiveConnections := -1
leastActiveServer := servers[0]
for _, server := range servers {
server.Mutex.Lock()
if (server.ActiveConnections < leastActiveConnections || leastActiveConnections == -1) &&
server.Healthy {
leastActiveConnections = server.ActiveConnections
leastActiveServer = server
}
server.Mutex.Unlock()
}
return leastActiveServer
}
func (s *Server) Proxy() *httputil.ReverseProxy {
return httputil.NewSingleHostReverseProxy(s.URL)
}
func main() {
config, err := loadConfig("config.json")
if err != nil {
log.Fatalf("Error loading configuration: %s", err.Error())
}
healthCheckInterval, err := time.ParseDuration(config.HealthCheckInterval)
if err != nil {
log.Fatalf("Invalid health check interval: %s", err.Error())
}
var servers []*Server
for _, serverUrl := range config.Servers {
u, _ := url.Parse(serverUrl)
servers = append(servers, &Server{URL: u})
}
for _, server := range servers {
go func(s *Server) {
for range time.Tick(healthCheckInterval) {
res, err := http.Get(s.URL.String())
if err != nil || res.StatusCode >= 500 {
s.Healthy = false
} else {
s.Healthy = true
}
}
}(server)
}
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
server := nextServerLeastActive(servers)
server.Mutex.Lock()
server.ActiveConnections++
server.Mutex.Unlock()
server.Proxy().ServeHTTP(w, r)
server.Mutex.Lock()
server.ActiveConnections--
server.Mutex.Unlock()
})
log.Println("Starting server on port", config.ListenPort)
err = http.ListenAndServe(config.ListenPort, nil)
if err != nil {
log.Fatalf("Error starting server: %s\n", err)
}
}