Implement graceful shutdowns

This commit is contained in:
2024-12-30 22:02:15 +01:00
parent b5a1bfc247
commit 218f56c060

View File

@ -5,11 +5,14 @@ package main
import (
db2 "code.dlmw.ch/dlmw/qv/internal/db"
"code.dlmw.ch/dlmw/qv/internal/models"
"context"
"database/sql"
_ "github.com/mattn/go-sqlite3"
"log/slog"
"net/http"
"os"
"os/signal"
"syscall"
"time"
)
@ -51,9 +54,12 @@ func main() {
WriteTimeout: 10 * time.Second,
}
err = srv.ListenAndServe()
logger.Error(err.Error())
os.Exit(1)
go watchForQuitSignals(srv, logger)
if err = srv.ListenAndServe(); err != nil {
logger.Error(err.Error())
os.Exit(1)
}
}
func openDb() (*sql.DB, error) {
@ -63,3 +69,17 @@ func openDb() (*sql.DB, error) {
}
return db, err
}
func watchForQuitSignals(srv *http.Server, logger *slog.Logger) {
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
s := <-quit
logger.Info("caught signal", "signal", s.String())
srv.Shutdown(ctx)
os.Exit(0)
}