diff --git a/main.go b/main.go index d1d9066..6d49ac5 100644 --- a/main.go +++ b/main.go @@ -1,8 +1,12 @@ package main import ( + "context" + "net/http" "github.com/labstack/echo/v4/middleware" "os" + "os/signal" + "time" "github.com/bumi/lndhub.go/database" "github.com/bumi/lndhub.go/lib" @@ -35,5 +39,21 @@ func main() { routes.Routes(e.Group("")) - e.Logger.Fatal(e.Start(":3000")) + // Start server + go func() { + if err := e.Start(":3000"); err != nil && err != http.ErrServerClosed { + e.Logger.Fatal("shutting down the server") + } + }() + + // Wait for interrupt signal to gracefully shutdown the server with a timeout of 10 seconds. + // Use a buffered channel to avoid missing signals as recommended for signal.Notify + quit := make(chan os.Signal, 1) + signal.Notify(quit, os.Interrupt) + <-quit + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + if err := e.Shutdown(ctx); err != nil { + e.Logger.Fatal(err) + } }