-
Notifications
You must be signed in to change notification settings - Fork 5
/
heartbeat.go
51 lines (45 loc) · 906 Bytes
/
heartbeat.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
package main
import (
"context"
"fmt"
"log"
"net/http"
"sync"
"time"
)
var (
mu sync.Mutex
lastHeartbeat time.Time
)
func updateHeartbeat() {
mu.Lock()
lastHeartbeat = time.Now()
mu.Unlock()
}
func heartbeatH(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
updateHeartbeat()
next.ServeHTTP(w, r)
})
}
func heartbeatF(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
updateHeartbeat()
next(w, r)
}
}
func checkHeartbeat(server *http.Server) {
for {
time.Sleep(5 * time.Second)
mu.Lock()
if time.Since(lastHeartbeat) > 10*time.Second {
fmt.Println("No active client, stopping server.")
mu.Unlock()
if err := server.Shutdown(context.Background()); err != nil {
log.Fatalf("Server shutdown failed: %+v", err)
}
break
}
mu.Unlock()
}
}