-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample_test.go
More file actions
94 lines (83 loc) · 2.27 KB
/
example_test.go
File metadata and controls
94 lines (83 loc) · 2.27 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
package launchcontrol
import (
"context"
"fmt"
"log/slog"
"net/http"
"os"
"os/signal"
"time"
)
func Example() {
ctx := context.TODO()
log := slog.New(slog.NewJSONHandler(os.Stderr, nil))
ctrl := New(ctx)
ctrl.SetLogger(log)
// A way for devs to easily test the shutdown behaviors.
signalCh := make(chan os.Signal, 1)
ctrl.Launch("sigint", Options{
Run: func(ctx context.Context) error {
signal.Notify(signalCh, os.Interrupt)
<-signalCh
signal.Stop(signalCh)
// Run returning triggers a shutdown
return nil
},
Stop: func(ctx context.Context) error {
signal.Stop(signalCh)
return nil
},
})
// A simple HTTP server; has the ability to shutdown via HTTP request, and signal if the service is ready.
var httpSrv http.Server
var httpReadyFlag bool
ctrl.Launch("http", Options{
Run: func(ctx context.Context) error {
mux := http.NewServeMux()
mux.HandleFunc("/_/ready", func(w http.ResponseWriter, r *http.Request) {
if httpReadyFlag {
w.WriteHeader(204)
} else {
w.WriteHeader(503)
}
})
mux.HandleFunc("/_/shutdown", func(w http.ResponseWriter, r *http.Request) {
ctrl.RequestStop(nil)
w.WriteHeader(204)
})
httpSrv = http.Server{
Addr: ":8080",
Handler: mux,
}
if err := httpSrv.ListenAndServe(); err == http.ErrServerClosed {
return nil
} else {
return err
}
},
Stop: func(ctx context.Context) error {
return httpSrv.Shutdown(ctx)
},
})
// And last but not least, we change the ready state as we startup and shutdown.
ctrl.Launch("ready-state", Options{
Start: func(ctx context.Context) error {
httpReadyFlag = true
fmt.Println("Application online. To quit, either:")
fmt.Println("* press ^C in terminal (dev)")
fmt.Println("* GET http://localhost:8080/_/shutdown")
return nil
},
Stop: func(ctx context.Context) error {
httpReadyFlag = false
// Wait after changing the ready state so our traffic management (envoy, isito, whatever) can detect
// that we're no longer ready and stop sending traffic our way.
fmt.Println("Waiting 15s for reverse proxies to notice us")
time.Sleep(15 * time.Second)
return nil
},
})
if err := ctrl.Wait(); err != nil {
log.Error("Launch Controller returned an error", "err", slog.AnyValue(err))
}
}