Improved clean exit handling

master
0x1a8510f2 2 years ago
parent 486c5dcc44
commit fd2ef31afa
Signed by: 0x1a8510f2
GPG Key ID: F5DE8E33A2723FF6
  1. 28
      main.go

@ -63,12 +63,26 @@ func main() {
browser.OpenURL(fmt.Sprintf("http://localhost:%d", port))
}
// Catch signals and exit gracefully
for sig := range routes.SharedMemory["sigchan"].(chan os.Signal) {
println(sig.String())
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
srv.Shutdown(ctx)
break
// Catch signals and exit gracefully upon receiving one. While we don't check the type
// of signal here, only exit signals are passed to this channel so there is no need
sig := <-routes.SharedMemory["sigchan"].(chan os.Signal)
// If another signal comes through, force exit
go func() {
sig := <-routes.SharedMemory["sigchan"].(chan os.Signal)
fmt.Printf("Received follow-up signal (`%s`). Forcing exit.\n", sig.String())
os.Exit(1)
}()
fmt.Printf("Received signal (`%s`). Exiting cleanly with timeout of 5 seconds. Resend to force exit.\n", sig.String())
// Tell HTTP server to exit with a timeout of 5 seconds
timeout := time.Duration(5 * time.Second)
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
err := srv.Shutdown(ctx)
if err != nil {
fmt.Printf("Shutting down the HTTP server failed with error (`%s`) but we will exit anyway.\n", err.Error())
}
}

Loading…
Cancel
Save