1
1
package main
2
2
3
3
import (
4
+ "context"
4
5
"encoding/json"
5
6
"fmt"
6
7
"mime"
7
8
"net/http"
9
+ "os"
10
+ "os/signal"
8
11
"sync"
12
+ "syscall"
9
13
"text/template"
10
14
"time"
11
15
@@ -72,6 +76,9 @@ func secretCleaner() {
72
76
73
77
func main () {
74
78
79
+ interrupt := make (chan os.Signal , 1 )
80
+ signal .Notify (interrupt , os .Interrupt , syscall .SIGTERM )
81
+
75
82
// Start loop that checks for expired secrets and deletes them
76
83
go secretCleaner ()
77
84
@@ -86,13 +93,32 @@ func main() {
86
93
87
94
r .HandleFunc ("/" , IndexHandler ).Methods ("GET" )
88
95
r .HandleFunc ("/" , NewHandler ).Methods ("POST" )
96
+ r .HandleFunc ("/healthz" , healthz )
89
97
r .PathPrefix ("/metrics" ).Handler (promhttp .HandlerFor (pr , promhttp.HandlerOpts {})).Methods ("GET" )
90
98
// r.HandleFunc("/metrics", promhttp.Handler()).Methods("GET")
91
99
r .HandleFunc ("/{id}" , GetHandler ).Methods ("GET" )
92
100
93
101
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
+ }()
94
109
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" )
96
122
}
97
123
98
124
func IndexHandler (w http.ResponseWriter , r * http.Request ) {
@@ -148,3 +174,8 @@ func GetHandler(w http.ResponseWriter, r *http.Request) {
148
174
w .WriteHeader (http .StatusOK )
149
175
fmt .Fprintf (w , "%s" , secretData )
150
176
}
177
+
178
+ // healthz is a liveness probe.
179
+ func healthz (w http.ResponseWriter , _ * http.Request ) {
180
+ w .WriteHeader (http .StatusOK )
181
+ }
0 commit comments