Graceful shutdown

This commit is contained in:
Jan-Lukas Else 2020-07-28 21:52:56 +02:00
parent 081259fca7
commit b57d1b2d2f
2 changed files with 25 additions and 2 deletions

21
http.go
View File

@ -1,10 +1,15 @@
package main
import (
"context"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
"log"
"net/http"
"os"
"os/signal"
"strconv"
"time"
)
func startServer() {
@ -19,7 +24,21 @@ func startServer() {
e.GET("/*", servePost)
address := ":" + strconv.Itoa(appConfig.server.port)
e.Logger.Fatal(e.Start(address))
go func() {
if err := e.Start(address); err != nil {
log.Println("Shutting down the server")
}
}()
// Wait for interrupt signal to gracefully shutdown the server with a timeout of 10 seconds.
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)
}
}
func hello(c echo.Context) error {

View File

@ -15,7 +15,11 @@ func main() {
log.Fatal(err)
}
defer func() {
log.Fatal(closeDb())
log.Println("Close database")
err := closeDb()
if err != nil {
log.Fatal(err)
}
}()
log.Println("Loaded database")
log.Println("Start server")