From 7969df1a38ac286058d6e83262dca13452cadbe2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Krystian=20Chachu=C5=82a?= Date: Mon, 1 Jul 2024 19:51:12 +0200 Subject: [PATCH] Add handling of SIGINT and SIGTERM Handle exit signals so that deferred calls are executed. It's mainly to unlink the socket before exiting. --- cmd/tokidoki/main.go | 28 +++++++++++++++++++++------- 1 file changed, 21 insertions(+), 7 deletions(-) diff --git a/cmd/tokidoki/main.go b/cmd/tokidoki/main.go index 06b817c..9d706fd 100644 --- a/cmd/tokidoki/main.go +++ b/cmd/tokidoki/main.go @@ -8,7 +8,9 @@ import ( "net" "net/http" "os" + "os/signal" "strings" + "syscall" "github.com/emersion/go-webdav" "github.com/emersion/go-webdav/caldav" @@ -189,12 +191,24 @@ func main() { log.Info().Str("address", addr).Msg("starting server") log.Debug().Msg("debug output enabled") - if (cert != "") && (key != "") { - err = server.ServeTLS(ln, cert, key) - } else { - err = server.Serve(ln) - } - if err != http.ErrServerClosed { - log.Fatal().Err(err).Msg("ListenAndServe() error") + go func() { + if (cert != "") && (key != "") { + err = server.ServeTLS(ln, cert, key) + } else { + err = server.Serve(ln) + } + if err != http.ErrServerClosed { + log.Fatal().Err(err).Msg("ListenAndServe() error") + } + }() + + sigCh := make(chan os.Signal, 1) + signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM) + for sig := range sigCh { + switch sig { + case syscall.SIGINT, syscall.SIGTERM: + server.Shutdown(context.Background()) + return + } } }