ch12.4
This commit is contained in:
@@ -1,6 +1,8 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"log"
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
@@ -20,23 +22,40 @@ func (app *application) serve() error {
|
|||||||
WriteTimeout: 10 * time.Second,
|
WriteTimeout: 10 * time.Second,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
shutdownError := make(chan error)
|
||||||
|
|
||||||
go func() {
|
go func() {
|
||||||
quit := make(chan os.Signal, 1)
|
quit := make(chan os.Signal, 1)
|
||||||
|
|
||||||
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
|
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
|
||||||
|
|
||||||
s := <-quit
|
s := <-quit
|
||||||
|
|
||||||
app.logger.PrintInfo("caught signal", map[string]string{
|
app.logger.PrintInfo("caught signal", map[string]string{
|
||||||
"signal": s.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{
|
app.logger.PrintInfo("starting server", map[string]string{
|
||||||
"addr": srv.Addr,
|
"addr": srv.Addr,
|
||||||
"env": app.config.env,
|
"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
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user