-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
78 lines (68 loc) · 1.79 KB
/
server.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
package golb
import (
"log"
"net/http"
"net/http/httputil"
"net/url"
"sync"
"time"
)
// server represents a load-balanced server interface.
type server interface {
Address() string
IsAlive() bool
Serve(http.ResponseWriter, *http.Request)
StartHealthCheck(interval time.Duration)
MarkUnhealthy()
}
// simpleServer represents a backend server with reverse proxy capabilities and health-check status.
type simpleServer struct {
addr string
proxy *httputil.ReverseProxy
isAlive bool
mu sync.Mutex
}
// newSimpleServer creates a new instance of simpleServer with reverse proxy and health-check status.
func newSimpleServer(addr string) *simpleServer {
serverUrl, err := url.Parse(addr)
if err != nil {
log.Fatalf("Failed to parse server URL %q: %v", addr, err)
}
return &simpleServer{
addr: addr,
proxy: httputil.NewSingleHostReverseProxy(serverUrl),
isAlive: true,
}
}
// Address returns the server address.
func (s *simpleServer) Address() string {
return s.addr
}
// IsAlive returns the current health status of the server.
func (s *simpleServer) IsAlive() bool {
s.mu.Lock()
defer s.mu.Unlock()
return s.isAlive
}
// MarkUnhealthy marks the server as unhealthy.
func (s *simpleServer) MarkUnhealthy() {
s.mu.Lock()
s.isAlive = false
s.mu.Unlock()
}
// Serve handles the HTTP request by forwarding it to the reverse proxy.
func (s *simpleServer) Serve(rw http.ResponseWriter, req *http.Request) {
s.proxy.ServeHTTP(rw, req)
}
// StartHealthCheck periodically checks the server’s health and updates its status.
func (s *simpleServer) StartHealthCheck(interval time.Duration) {
go func() {
for {
resp, err := http.Get(s.addr + "/health")
s.mu.Lock()
s.isAlive = err == nil && resp.StatusCode == http.StatusOK
s.mu.Unlock()
time.Sleep(interval)
}
}()
}