Skip to content

Commit eaaec7e

Browse files
committed
added /healthz endpoint and graceful shutdown
1 parent d349229 commit eaaec7e

File tree

1 file changed

+32
-1
lines changed

1 file changed

+32
-1
lines changed

main.go

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,15 @@
11
package main
22

33
import (
4+
"context"
45
"encoding/json"
56
"fmt"
67
"mime"
78
"net/http"
9+
"os"
10+
"os/signal"
811
"sync"
12+
"syscall"
913
"text/template"
1014
"time"
1115

@@ -72,6 +76,9 @@ func secretCleaner() {
7276

7377
func main() {
7478

79+
interrupt := make(chan os.Signal, 1)
80+
signal.Notify(interrupt, os.Interrupt, syscall.SIGTERM)
81+
7582
// Start loop that checks for expired secrets and deletes them
7683
go secretCleaner()
7784

@@ -86,13 +93,32 @@ func main() {
8693

8794
r.HandleFunc("/", IndexHandler).Methods("GET")
8895
r.HandleFunc("/", NewHandler).Methods("POST")
96+
r.HandleFunc("/healthz", healthz)
8997
r.PathPrefix("/metrics").Handler(promhttp.HandlerFor(pr, promhttp.HandlerOpts{})).Methods("GET")
9098
// r.HandleFunc("/metrics", promhttp.Handler()).Methods("GET")
9199
r.HandleFunc("/{id}", GetHandler).Methods("GET")
92100

93101
port := 8080
102+
srv := &http.Server{
103+
Addr: fmt.Sprintf(":%d", port),
104+
Handler: r,
105+
}
106+
go func() {
107+
log.Fatal().Err(srv.ListenAndServe()).Msgf("Unable to run the server at port %d", port)
108+
}()
94109
log.Info().Msgf("Starting server at port %d", port)
95-
log.Fatal().Err(http.ListenAndServe(fmt.Sprintf(":%d", port), r)).Msgf("Unable to start server at port %d", port)
110+
111+
killSignal := <-interrupt
112+
switch killSignal {
113+
case os.Interrupt:
114+
log.Info().Msg("Got SIGINT...")
115+
case syscall.SIGTERM:
116+
log.Info().Msg("Got SIGTERM...")
117+
}
118+
119+
log.Info().Msg("The service is shutting down...")
120+
srv.Shutdown(context.Background())
121+
log.Info().Msg("Done")
96122
}
97123

98124
func IndexHandler(w http.ResponseWriter, r *http.Request) {
@@ -148,3 +174,8 @@ func GetHandler(w http.ResponseWriter, r *http.Request) {
148174
w.WriteHeader(http.StatusOK)
149175
fmt.Fprintf(w, "%s", secretData)
150176
}
177+
178+
// healthz is a liveness probe.
179+
func healthz(w http.ResponseWriter, _ *http.Request) {
180+
w.WriteHeader(http.StatusOK)
181+
}

0 commit comments

Comments
 (0)