From 913a076c526a84dadf161f090f20d9ca705568c2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thorben=20G=C3=BCnther?= Date: Mon, 17 Jul 2023 16:39:16 +0200 Subject: [PATCH] Implement graceful shutdown --- main.go | 39 +++++++++++++++++++++++++++++++++------ 1 file changed, 33 insertions(+), 6 deletions(-) diff --git a/main.go b/main.go index f3ff93c..748d5eb 100644 --- a/main.go +++ b/main.go @@ -2,6 +2,7 @@ package main import ( + "context" "crypto/sha512" "crypto/subtle" _ "embed" @@ -11,7 +12,9 @@ import ( "fmt" "net/http" "os" + "os/signal" "strings" + "syscall" "time" "git.xenrox.net/~xenrox/go-log" @@ -411,11 +414,15 @@ func (br *bridge) basicAuthMiddleware(handler http.HandlerFunc) http.HandlerFunc } } -func (br *bridge) runCleanup() { +func (br *bridge) runCleanup(ctx context.Context) { for { - time.Sleep(br.cfg.Cache.CleanupInterval) - br.logger.Info("Pruning cache") - br.cache.Cleanup() + select { + case <-time.After(br.cfg.Cache.CleanupInterval): + br.logger.Info("Pruning cache") + br.cache.Cleanup() + case <-ctx.Done(): + return + } } } @@ -442,6 +449,9 @@ func main() { logger.Errorf("Failed to parse logging level: %v", err) } + ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) + defer stop() + client := &httpClient{&http.Client{Timeout: time.Second * 3}} c, err := cache.NewCache(cfg.Cache) @@ -468,7 +478,24 @@ func main() { } if _, ok := c.(*cache.MemoryCache); ok { - go bridge.runCleanup() + go bridge.runCleanup(ctx) + } + + go func() { + err = httpServer.ListenAndServe() + if err != nil && err != http.ErrServerClosed { + logger.Fatalf("Failed to start HTTP server: %v", err) + } + }() + + <-ctx.Done() + stop() + + httpShutdownContext, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + err = httpServer.Shutdown(httpShutdownContext) + if err != nil { + logger.Errorf("Failed to shutdown HTTP server: %v", err) } - logger.Fatal(httpServer.ListenAndServe()) }