http_graceful.go
func Graceful(start StartFunc, shutdown ShutdownFunc) error {
	var (
		stopChan = make(chan os.Signal)
		errChan  = make(chan error)
	)

	// Setup the graceful shutdown handler (traps SIGINT and SIGTERM)
	go func() {
		signal.Notify(stopChan, os.Interrupt, syscall.SIGTERM)

		<-stopChan

		timer, cancel := context.WithTimeout(context.Background(), DefaultShutdownTimeout)
		defer cancel()

		if err := shutdown(timer); err != nil {
			errChan <- errors.WithStack(err)
			return
		}

		errChan <- nil
	}()

	// Start the server
	if err := start(); err != http.ErrServerClosed {
		return err
	}

	return <-errChan
}
func Graceful(start StartFunc, shutdown ShutdownFunc) error {
	var (
		stopChan = make(chan os.Signal)
		errChan  = make(chan error)
	)

	// Setup the graceful shutdown handler (traps SIGINT and SIGTERM)
	go func() {
		signal.Notify(stopChan, os.Interrupt, syscall.SIGTERM)

		<-stopChan

		timer, cancel := context.WithTimeout(context.Background(), DefaultShutdownTimeout)
		defer cancel()

		if err := shutdown(timer); err != nil {
			errChan <- errors.WithStack(err)
			return
		}

		errChan <- nil
	}()

	// Start the server
	if err := start(); err != http.ErrServerClosed {
		return err
	}

	return <-errChan
}
func Graceful ( start StartFunc , shutdown ShutdownFunc ) error { var ( stopChan = make ( chan os . Signal ) errChan = make ( chan error ) ) // Setup the graceful shutdown handler (traps SIGINT and SIGTERM) go func ( ) { signal . Notify ( stopChan , os . Interrupt , syscall . SIGTERM ) <- stopChan timer , cancel := context . WithTimeout ( context . Background ( ) , DefaultShutdownTimeout ) defer cancel ( ) if err := shutdown ( timer ) ; err != nil { errChan <- errors . WithStack ( err ) return } errChan <- nil } ( ) // Start the server if err := start ( ) ; err != http . ErrServerClosed { return err } return <- errChan }
// Graceful sets up graceful handling of SIGINT and SIGTERM, typically for an HTTP server.
// When signal is trapped, the shutdown handler will be invoked with a context that expires
// after DefaultShutdownTimeout (5s).
//
//   server := graceful.WithDefaults(http.Server{})
//
//   if err := graceful.Graceful(server.ListenAndServe, server.Shutdown); err != nil {
//	   log.Fatal("Failed to gracefully shut down")
//   }
Graceful sets up graceful handling of SIGINT and SIGTERM typically for an HTTP server . When signal is trapped the shutdown handler will be invoked with a context that expires after DefaultShutdownTimeout ( 5s ) . server : = graceful . WithDefaults ( http . Server {} ) if err : = graceful . Graceful ( server . ListenAndServe server . Shutdown ) ; err ! = nil { log . Fatal ( Failed to gracefully shut down ) }