From 9ee523465b1a05f6d94bb3761b3c5b56de38c63f Mon Sep 17 00:00:00 2001 From: Namekuji Date: Sat, 10 Dec 2022 08:16:34 -0500 Subject: [PATCH] add graceful shutdown --- server.go | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/server.go b/server.go index 40192fd..805b7bc 100644 --- a/server.go +++ b/server.go @@ -9,6 +9,7 @@ import ( "net/http" "net/url" "os" + "os/signal" "time" "github.com/go-playground/validator/v10" @@ -137,7 +138,24 @@ func main() { e.Static("/assets", "audon-fe/dist/assets") e.File("/*", "audon-fe/dist/index.html") - e.Logger.Debug(e.Start(":8100")) + // use anonymous func to support graceful shutdown + go func() { + if err := e.Start(":1323"); err != nil && err != http.ErrServerClosed { + e.Logger.Fatal("shutting down the server") + } + }() + + // Wait for interrupt signal to gracefully shutdown the server with a timeout of 10 seconds. + // Use a buffered channel to avoid missing signals as recommended for signal.Notify + quit := make(chan os.Signal, 1) + signal.Notify(quit, os.Interrupt) + <-quit + shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 10*time.Second) + e.Logger.Print("Attempting graceful shutdown") + defer shutdownCancel() + if err := e.Shutdown(shutdownCtx); err != nil { + e.Logger.Fatal(err) + } } func (t *Template) Render(w io.Writer, name string, data interface{}, c echo.Context) error {