update readme graceful shutdown example

This commit is contained in:
Lovecanon 2022-07-01 09:41:17 +08:00
parent 92dd245c9b
commit e21a9efb97
1 changed files with 26 additions and 19 deletions

View File

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