mirror of https://github.com/gin-gonic/gin.git
update readme graceful shutdown example
This commit is contained in:
parent
92dd245c9b
commit
e21a9efb97
39
README.md
39
README.md
|
@ -1831,31 +1831,38 @@ 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...")
|
||||
|
||||
// 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()
|
||||
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 {
|
||||
log.Fatal("Server forced to shutdown:", err)
|
||||
if err := srv.Shutdown(ctx); err != nil {
|
||||
srv.Close()
|
||||
log.Fatal("Server forced to shutdown:", err)
|
||||
}
|
||||
}
|
||||
|
||||
log.Println("Server exiting")
|
||||
|
|
Loading…
Reference in New Issue