diff --git a/cmd/api/helpers.go b/cmd/api/helpers.go index a700956..308732e 100644 --- a/cmd/api/helpers.go +++ b/cmd/api/helpers.go @@ -122,12 +122,16 @@ func (app *application) readInt(qs url.Values, key string, defaultValue int, v * } func (app *application) background(fn func()) { + app.wg.Add(1) go func() { + defer app.wg.Done() + defer func() { if err := recover(); err != nil { app.logger.PrintError(fmt.Errorf("%s", err), nil) } }() + fn() }() } diff --git a/cmd/api/main.go b/cmd/api/main.go index 510a575..4077a09 100644 --- a/cmd/api/main.go +++ b/cmd/api/main.go @@ -5,6 +5,7 @@ import ( "database/sql" "flag" "os" + "sync" "time" "gitea.local.lab/Lbenedar/greenlight/internal/data" @@ -20,6 +21,7 @@ type application struct { logger *jsonlog.Logger models data.Models mailer mailer.Mailer + wg sync.WaitGroup } type config struct { diff --git a/cmd/api/server.go b/cmd/api/server.go index 454100a..a689896 100644 --- a/cmd/api/server.go +++ b/cmd/api/server.go @@ -36,7 +36,18 @@ func (app *application) serve() error { ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() - shutdownError <- srv.Shutdown(ctx) + err := srv.Shutdown(ctx) + if err != nil { + shutdownError <- err + } + + app.logger.PrintInfo("completing background tasks", map[string]string{ + "addr": srv.Addr, + }) + + app.wg.Wait() + shutdownError <- nil + }() app.logger.PrintInfo("starting server", map[string]string{ @@ -49,13 +60,14 @@ func (app *application) serve() error { return err } + app.logger.PrintInfo("stopped server", map[string]string{ + "addr": srv.Addr, + }) + err = <-shutdownError if err != nil { return err } - app.logger.PrintInfo("stopped server", map[string]string{ - "addr": srv.Addr, - }) return nil }