From 55e1bdb8421a5b6da54dd50a83a015c5959dd772 Mon Sep 17 00:00:00 2001 From: Patrick Date: Wed, 21 Aug 2024 11:07:03 +0200 Subject: [PATCH] (BEDS-90) api: shut down server gracefully (#681) --- backend/cmd/api/main.go | 35 ++++++++++++++++++++++++------ backend/pkg/commons/utils/utils.go | 3 ++- 2 files changed, 30 insertions(+), 8 deletions(-) diff --git a/backend/cmd/api/main.go b/backend/cmd/api/main.go index 2834f96d8..1df0d4bd1 100644 --- a/backend/cmd/api/main.go +++ b/backend/cmd/api/main.go @@ -1,6 +1,8 @@ package main import ( + "context" + "errors" "flag" "net" "net/http" @@ -69,12 +71,31 @@ func main() { router.Use(ratelimit.HttpMiddleware) } - srv := &http.Server{ - Handler: router, - Addr: net.JoinHostPort(cfg.Frontend.Server.Host, cfg.Frontend.Server.Port), - WriteTimeout: 15 * time.Second, - ReadTimeout: 15 * time.Second, + var srv *http.Server + go func() { + srv = &http.Server{ + Handler: router, + Addr: net.JoinHostPort(cfg.Frontend.Server.Host, cfg.Frontend.Server.Port), + WriteTimeout: 15 * time.Second, + ReadTimeout: 15 * time.Second, + } + log.Infof("serving on %s:%s", cfg.Frontend.Server.Host, cfg.Frontend.Server.Port) + if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { + log.Fatal(err, "error serving", 0) + } + }() + + utils.WaitForCtrlC() + + log.Info("shutting down server") + if srv != nil { + shutDownCtx, cancelShutDownCtx := context.WithTimeout(context.Background(), 10*time.Second) + defer cancelShutDownCtx() + err = srv.Shutdown(shutDownCtx) + if err != nil { + log.Error(err, "error shutting down server", 0) + } else { + log.Info("server shut down") + } } - log.Infof("Serving on %s:%s", cfg.Frontend.Server.Host, cfg.Frontend.Server.Port) - log.Fatal(srv.ListenAndServe(), "Error while serving", 0) } diff --git a/backend/pkg/commons/utils/utils.go b/backend/pkg/commons/utils/utils.go index fac769cb2..c84aca8d3 100644 --- a/backend/pkg/commons/utils/utils.go +++ b/backend/pkg/commons/utils/utils.go @@ -16,6 +16,7 @@ import ( "sort" "strconv" "strings" + "syscall" "time" "unicode/utf8" @@ -156,7 +157,7 @@ func fixUtf(r rune) rune { func WaitForCtrlC() { c := make(chan os.Signal, 1) - signal.Notify(c, os.Interrupt) + signal.Notify(c, os.Interrupt, syscall.SIGINT, syscall.SIGTERM) <-c }