diff --git a/cmd/any2anexoj-web/main.go b/cmd/any2anexoj-web/main.go index 5aa84ff..825047c 100644 --- a/cmd/any2anexoj-web/main.go +++ b/cmd/any2anexoj-web/main.go @@ -13,6 +13,7 @@ import ( "time" "github.com/nmoniz/any2anexoj/internal/web" + "golang.org/x/sync/errgroup" ) //go:embed all:static @@ -23,6 +24,7 @@ func main() { slog.Error("any2anexoj-web: fatal error", slog.Any("err", err)) os.Exit(1) } + slog.Info("shutdown gracefully") } // 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) defer cancel() - errCh := make(chan error, 1) - go func() { - slog.Info("any2anexoj-web: listening", slog.String("addr", addr)) - if err := httpServer.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { - errCh <- err - return + eg, ctx := errgroup.WithContext(ctx) + + eg.Go(func() error { + slog.Info("listening for http", slog.Any("port", addr)) + err := httpServer.ListenAndServe() + 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) defer shutdownCancel() + if err := httpServer.Shutdown(shutdownCtx); err != nil { return err } return nil - case err := <-errCh: - return err - } + }) + + return eg.Wait() }