Graceful Shutdown

Using http.Server#Shutdown()

server.go

  1. package main
  2. import (
  3. "context"
  4. "net/http"
  5. "os"
  6. "os/signal"
  7. "time"
  8. "github.com/labstack/echo"
  9. "github.com/labstack/gommon/log"
  10. )
  11. func main() {
  12. // Setup
  13. e := echo.New()
  14. e.Logger.SetLevel(log.INFO)
  15. e.GET("/", func(c echo.Context) error {
  16. time.Sleep(5 * time.Second)
  17. return c.JSON(http.StatusOK, "OK")
  18. })
  19. // Start server
  20. go func() {
  21. if err := e.Start(":1323"); err != nil {
  22. e.Logger.Info("shutting down the server")
  23. }
  24. }()
  25. // Wait for interrupt signal to gracefully shutdown the server with
  26. // a timeout of 10 seconds.
  27. quit := make(chan os.Signal)
  28. signal.Notify(quit, os.Interrupt)
  29. <-quit
  30. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  31. defer cancel()
  32. if err := e.Shutdown(ctx); err != nil {
  33. e.Logger.Fatal(err)
  34. }
  35. }

Requires go1.8+

Using grace

server.go

  1. package main
  2. import (
  3. "net/http"
  4. "github.com/facebookgo/grace/gracehttp"
  5. "github.com/labstack/echo"
  6. )
  7. func main() {
  8. // Setup
  9. e := echo.New()
  10. e.GET("/", func(c echo.Context) error {
  11. return c.String(http.StatusOK, "Six sick bricks tick")
  12. })
  13. e.Server.Addr = ":1323"
  14. // Serve it like a boss
  15. e.Logger.Fatal(gracehttp.Serve(e.Server))
  16. }

Using graceful

server.go

  1. package main
  2. import (
  3. "net/http"
  4. "time"
  5. "github.com/labstack/echo"
  6. "github.com/tylerb/graceful"
  7. )
  8. func main() {
  9. // Setup
  10. e := echo.New()
  11. e.GET("/", func(c echo.Context) error {
  12. return c.String(http.StatusOK, "Sue sews rose on slow joe crows nose")
  13. })
  14. e.Server.Addr = ":1323"
  15. // Serve it like a boss
  16. graceful.ListenAndServe(e.Server, 5*time.Second)
  17. }

Source Code

Maintainers