fix/simplify server startup/shutdown
Alan Pearce alan@alanpearce.eu
Tue, 18 Jun 2024 15:54:10 +0200
1 files changed, 16 insertions(+), 24 deletions(-)
jump to
M cmd/server/main.go → cmd/server/main.go
@@ -1,10 +1,10 @@ package main import ( + "context" "fmt" "os" "os/signal" - "sync" "website/internal/log" "website/internal/server" @@ -39,34 +39,26 @@ runtimeConfig.Root = tmpdir defer os.RemoveAll(tmpdir) } - c := make(chan os.Signal, 2) - signal.Notify(c, os.Interrupt) sv, err := server.New(&runtimeConfig) if err != nil { - log.Fatal("error setting up server", "error", err) + log.Error("could not create server", "error", err) + + return } - wg := &sync.WaitGroup{} - wg.Add(1) - go func() { - defer wg.Done() - sig := <-c - log.Info("signal captured", "sig", sig) - <-sv.Stop() - log.Debug("server stopped") - }() - sErr := make(chan error) - wg.Add(1) + ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt) + defer cancel() + go func() { - defer wg.Done() - sErr <- sv.Start() + err = sv.Start() + if err != nil { + // Error starting or closing listener: + log.Fatal("error %v", err) + } }() - log.Info("server listening", "address", sv.Addr) - err = <-sErr - if err != nil { - // Error starting or closing listener: - log.Fatal("error", "error", err) - } - wg.Wait() + <-ctx.Done() + log.Debug("calling stop") + sv.Stop() + log.Debug("done") }