diff --git a/cmd/api/server.go b/cmd/api/server.go index d2c3b92..454100a 100644 --- a/cmd/api/server.go +++ b/cmd/api/server.go @@ -1,6 +1,8 @@ package main import ( + "context" + "errors" "fmt" "log" "net/http" @@ -20,23 +22,40 @@ func (app *application) serve() error { WriteTimeout: 10 * time.Second, } + shutdownError := make(chan error) + go func() { quit := make(chan os.Signal, 1) - signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM) - s := <-quit app.logger.PrintInfo("caught signal", map[string]string{ "signal": s.String(), }) - os.Exit(0) + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + + shutdownError <- srv.Shutdown(ctx) }() app.logger.PrintInfo("starting server", map[string]string{ "addr": srv.Addr, "env": app.config.env, }) - return srv.ListenAndServe() + + err := srv.ListenAndServe() + if !errors.Is(err, http.ErrServerClosed) { + return err + } + + err = <-shutdownError + if err != nil { + return err + } + + app.logger.PrintInfo("stopped server", map[string]string{ + "addr": srv.Addr, + }) + return nil }