socialpredict icon indicating copy to clipboard operation
socialpredict copied to clipboard

Add Graceful Shutdown to HTTP Server

Open avalonprod opened this issue 1 year ago • 1 comments

You can use this code to shut down your application smoothly.

	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGTERM, syscall.SIGINT)

	<-quit
	const timeout = 5 * time.Second

	ctx, shutdown := context.WithTimeout(context.Background(), timeout)
	defer shutdown()
	if err := srv.Shotdown(ctx); err != nil {
		logger.Errorf("failed to stop server: %x", err)
	}

You can use the context to terminate the server or database. For example:

func (s *Server) Shotdown(ctx context.Context) error {
	return s.httpServer.Shutdown(ctx)
}

or you can simply warn the system that the application is shutting down.

avalonprod avatar Feb 07 '24 20:02 avalonprod

Great idea, thank you.

pwdel avatar Feb 07 '24 23:02 pwdel