From 264414195350e153794333b761a24d825e8bf821 Mon Sep 17 00:00:00 2001 From: konrad Date: Fri, 1 Dec 2017 12:46:47 +0100 Subject: [PATCH] Implemented graceful shutdown --- main.go | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/main.go b/main.go index 4becc47..7997e23 100644 --- a/main.go +++ b/main.go @@ -5,6 +5,10 @@ import ( "git.mowie.cc/konrad/Library/routes" "fmt" + "os" + "time" + "os/signal" + "context" ) // UserLogin Object to recive user credentials in JSON format @@ -30,5 +34,22 @@ func main() { // Start the webserver e := routes.NewEcho() routes.RegisterRoutes(e) - e.Start(models.Config.Interface) + // Start server + go func() { + if err := e.Start(models.Config.Interface); err != nil { + e.Logger.Info("shutting down the server") + } + }() + + // Wait for interrupt signal to gracefully shutdown the server with + // a timeout of 10 seconds. + quit := make(chan os.Signal) + signal.Notify(quit, os.Interrupt) + <-quit + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + fmt.Println("Shutting down...") + if err := e.Shutdown(ctx); err != nil { + e.Logger.Fatal(err) + } }