better lifecycle management

This commit is contained in:
natercio committed 2026-09-28 21:46:54 +01:00
1 parent d32f2b3a66
commit 4604175e8d
1 file changed
+18 -14
+18 -14
View File
@@ -13,6 +13,7 @@ import (
"time" "time"
"github.com/nmoniz/any2anexoj/internal/web" "github.com/nmoniz/any2anexoj/internal/web"
"golang.org/x/sync/errgroup"
) )
//go:embed all:static //go:embed all:static
@@ -23,6 +24,7 @@ func main() {
slog.Error("any2anexoj-web: fatal error", slog.Any("err", err)) slog.Error("any2anexoj-web: fatal error", slog.Any("err", err))
os.Exit(1) os.Exit(1)
} }
slog.Info("shutdown gracefully")
} }
// run wires up the server, installs signal-driven cancellation, and blocks on // run wires up the server, installs signal-driven cancellation, and blocks on
@@ -60,26 +62,28 @@ func run() error {
ctx, cancel := signal.NotifyContext(context.Background(), os.Kill, os.Interrupt, syscall.SIGTERM) ctx, cancel := signal.NotifyContext(context.Background(), os.Kill, os.Interrupt, syscall.SIGTERM)
defer cancel() defer cancel()
errCh := make(chan error, 1) eg, ctx := errgroup.WithContext(ctx)
go func() {
slog.Info("any2anexoj-web: listening", slog.String("addr", addr)) eg.Go(func() error {
if err := httpServer.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { slog.Info("listening for http", slog.Any("port", addr))
errCh <- err err := httpServer.ListenAndServe()
return if err != nil && !errors.Is(err, http.ErrServerClosed) {
return err
} }
errCh <- nil return nil
}() })
eg.Go(func() error {
<-ctx.Done()
select {
case <-ctx.Done():
slog.Info("any2anexoj-web: shutting down")
shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 10*time.Second) shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 10*time.Second)
defer shutdownCancel() defer shutdownCancel()
if err := httpServer.Shutdown(shutdownCtx); err != nil { if err := httpServer.Shutdown(shutdownCtx); err != nil {
return err return err
} }
return nil return nil
case err := <-errCh: })
return err
} return eg.Wait()
} }