From a31e549740cef797778b6a8009da5a62b633be0e Mon Sep 17 00:00:00 2001 From: Vargha Csongor Date: Sat, 23 Mar 2024 19:01:35 +0100 Subject: [PATCH] Add gracefull shutdown server --- backend/main.go | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/backend/main.go b/backend/main.go index 3e5de2e..e5e97bc 100644 --- a/backend/main.go +++ b/backend/main.go @@ -1,11 +1,15 @@ package main import ( + "context" "flag" "fmt" "io" "log" + "net/http" "os" + "os/signal" + "syscall" "time" "github.com/gin-gonic/gin" @@ -48,4 +52,28 @@ func main() { router := gin.Default() router.GET("/health", hc.HealthCheckHandler()) + + //Server configuration + var server *http.Server + + // Wait for interrupt signal to gracefully shutdown the server with + // a timeout of 5 seconds. + quit := make(chan os.Signal, 1) + // kill (no param) default send syscall.SIGTERM + // kill -2 is syscall.SIGINT + // kill -9 is syscall.SIGKILL but can't be caught, so don't need to add it + signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM, os.Interrupt) + <-quit + log.Println("Shutting down server...") + + // The context is used to inform the server it has 5 seconds to finish + // the request it is currently handling + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + + if err := server.Shutdown(ctx); err != nil { + log.Fatal("Server forced to shutdown:", err) + } + + log.Println("Server exiting") }