-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
149 lines (123 loc) · 3.7 KB
/
Copy pathmain.go
File metadata and controls
149 lines (123 loc) · 3.7 KB
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
package main
import (
"context"
"errors"
"fmt"
"net/http"
"os"
"os/signal"
"strconv"
"strings"
"syscall"
"time"
)
const (
serverAddress = ":8080"
healthFailureEvery = 30 * time.Minute
healthFailureDuration = 10 * time.Minute
readyAfter = 2 * time.Minute
)
type healthChecker struct {
startedAt time.Time
now func() time.Time
}
type readinessChecker struct {
startedAt time.Time
now func() time.Time
}
func newHealthChecker(startedAt time.Time) healthChecker {
return healthChecker{
startedAt: startedAt,
now: time.Now,
}
}
func newReadinessChecker(startedAt time.Time) readinessChecker {
return readinessChecker{
startedAt: startedAt,
now: time.Now,
}
}
func (checker healthChecker) isHealthy() bool {
elapsed := checker.now().Sub(checker.startedAt)
if elapsed < healthFailureEvery {
return true
}
return elapsed%healthFailureEvery >= healthFailureDuration
}
func (checker readinessChecker) isReady() bool {
return checker.now().Sub(checker.startedAt) >= readyAfter
}
func RootServer(w http.ResponseWriter, r *http.Request) {
fmt.Printf("Received request for %s\n", r.URL.Path)
fmt.Fprintf(w, "Welcome to the root path! Use /slow for a delayed response. Use /hello/{name} to get a personalized greeting.")
}
func HelloServer(w http.ResponseWriter, r *http.Request) {
fmt.Printf("Received request for %s\n", r.URL.Path)
name := strings.TrimPrefix(r.URL.Path, "/hello/")
name = strings.Trim(name, "/")
if name == "" {
http.Error(w, "please provide a name in /hello/{name}", http.StatusBadRequest)
return
}
fmt.Fprintf(w, "Hello, %s!", name)
}
func SlowHelloServer(w http.ResponseWriter, r *http.Request) {
delaySeconds := 5
if raw := r.URL.Query().Get("seconds"); raw != "" {
if parsed, err := strconv.Atoi(raw); err == nil && parsed >= 0 && parsed <= 10 {
delaySeconds = parsed
}
}
delay := time.Duration(delaySeconds) * time.Second
start := time.Now()
fmt.Printf("Started /slow request with %ds delay\n", delaySeconds)
time.Sleep(delay)
fmt.Fprintf(w, "Slow response after %v\n", time.Since(start).Round(100*time.Millisecond))
}
func HealthServer(checker healthChecker) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
fmt.Printf("Received request for %s\n", r.URL.Path)
if checker.isHealthy() {
fmt.Fprintln(w, "ok")
return
}
http.Error(w, "unhealthy", http.StatusServiceUnavailable)
}
}
func ReadyServer(checker readinessChecker) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
fmt.Printf("Received request for %s\n", r.URL.Path)
if checker.isReady() {
fmt.Fprintln(w, "ready")
return
}
http.Error(w, "not ready", http.StatusServiceUnavailable)
}
}
func main() {
fmt.Println("Starting web server")
startTime := time.Now()
health := newHealthChecker(startTime)
ready := newReadinessChecker(startTime)
http.HandleFunc("/", RootServer)
http.HandleFunc("/hello/", HelloServer)
http.HandleFunc("/slow", SlowHelloServer)
http.HandleFunc("/healthz", HealthServer(health))
http.HandleFunc("/ready", ReadyServer(ready))
server := &http.Server{Addr: serverAddress, Handler: nil}
go func() {
fmt.Printf("Web server is running on http://localhost%s ...\n", serverAddress)
if err := server.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
fmt.Println("Server stopped:", err)
}
}()
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
<-ctx.Done()
fmt.Println("Shutdown signal received")
shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := server.Shutdown(shutdownCtx); err != nil {
fmt.Println("Graceful shutdown failed:", err)
}
}