Merge e21a9efb978a3d6c5849daecb1ad98f948f56229 into b57163a0e4339d7feb393ff430a454f4e448cf9c

This commit is contained in:
Lovecanon 2022-07-05 12:50:31 +09:00 committed by GitHub
commit 3aa0a7cbb6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1831,32 +1831,39 @@ func main() {
Handler: router,
}
// Initializing the server in a goroutine so that
// it won't block the graceful shutdown handling below
go func() {
if err := srv.ListenAndServe(); err != nil && errors.Is(err, http.ErrServerClosed) {
log.Printf("listen: %s\n", err)
}
}()
// Receive another goroutine listen error
serverError := make(chan error, 1)
// Wait for interrupt signal to gracefully shutdown the server with
// a timeout of 5 seconds.
quit := make(chan os.Signal)
quit := make(chan os.Signal, 1)
// Initializing the server in a goroutine so that
// it won't block the graceful shutdown handling below
go func() {
serverError <- srv.ListenAndServe()
}()
// kill (no param) default send syscall.SIGTERM
// kill -2 is syscall.SIGINT
// kill -9 is syscall.SIGKILL but can't be caught, so don't need to add it
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit
log.Println("Shutting down server...")
select {
case err := <-serverError:
log.Printf("listen: %s\n", err)
case <-quit:
log.Println("Shutting down server...")
// The context is used to inform the server it has 5 seconds to finish
// the request it is currently handling
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
srv.Close()
log.Fatal("Server forced to shutdown:", err)
}
}
log.Println("Server exiting")
}