This commit is contained in:
lbenedar
2026-03-19 18:38:22 +03:00
parent 46a1bb868b
commit 16f2caee66
3 changed files with 22 additions and 4 deletions

View File

@@ -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()
}()
}

View File

@@ -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 {

View File

@@ -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
}