go: handle SIGINT gracefully

This commit is contained in:
leo 2023-03-22 22:56:25 +01:00
parent 6194f36d73
commit f728a9750f
Signed by: wanderer
SSH Key Fingerprint: SHA256:Dp8+iwKHSlrMEHzE3bJnPng70I7LEsa3IJXRH/U+idQ

23
run.go

@ -1,8 +1,12 @@
package main package main
import ( import (
"context"
"flag" "flag"
"net/http" "net/http"
"os"
"os/signal"
"time"
"git.dotya.ml/mirre-mt/pcmt/app" "git.dotya.ml/mirre-mt/pcmt/app"
"git.dotya.ml/mirre-mt/pcmt/config" "git.dotya.ml/mirre-mt/pcmt/config"
@ -37,7 +41,24 @@ func run() error {
return c.String(http.StatusOK, "Hello there.") return c.String(http.StatusOK, "Hello there.")
}) })
if err = e.Start(*addr); err != nil { go func() {
if err = e.Start(*addr); err != nil && err != http.ErrServerClosed {
logger.Println("shutting down the server")
}
}()
quit := make(chan os.Signal, 1)
signal.Notify(quit, os.Interrupt)
<-quit
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer func() {
logger.Println("Interrupt received, gracefully shutting down the server")
cancel()
}()
if err = e.Shutdown(ctx); err != nil {
return err return err
} }