Graceful restart or stop

Do you want to graceful restart or stop your web server?
There are some ways this can be done.

We can use fvbock/endless to replace the default ListenAndServe. Refer issue #296 for more details.

  1. router := gin.Default()
  2. router.GET("/", handler)
  3. // [...]
  4. endless.ListenAndServe(":4242", router)

An alternative to endless:

  • manners: A polite Go HTTP server that shuts down gracefully.
  • graceful: Graceful is a Go package enabling graceful shutdown of an http.Handler server.
  • grace: Graceful restart & zero downtime deploy for Go servers.

If you are using Go 1.8, you may not need to use this library! Consider using http.Server’s built-in Shutdown() method for graceful shutdowns. See the full graceful-shutdown example with gin.

  1. // +build go1.8
  2. package main
  3. import (
  4. "context"
  5. "log"
  6. "net/http"
  7. "os"
  8. "os/signal"
  9. "time"
  10. "github.com/gin-gonic/gin"
  11. )
  12. func main() {
  13. router := gin.Default()
  14. router.GET("/", func(c *gin.Context) {
  15. time.Sleep(5 * time.Second)
  16. c.String(http.StatusOK, "Welcome Gin Server")
  17. })
  18. srv := &http.Server{
  19. Addr: ":8080",
  20. Handler: router,
  21. }
  22. go func() {
  23. // service connections
  24. if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
  25. log.Fatalf("listen: %s\n", err)
  26. }
  27. }()
  28. // Wait for interrupt signal to gracefully shutdown the server with
  29. // a timeout of 5 seconds.
  30. quit := make(chan os.Signal)
  31. signal.Notify(quit, os.Interrupt)
  32. <-quit
  33. log.Println("Shutdown Server ...")
  34. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  35. defer cancel()
  36. if err := srv.Shutdown(ctx); err != nil {
  37. log.Fatal("Server Shutdown:", err)
  38. }
  39. log.Println("Server exiting")
  40. }