feat: graceful shutdown server (#1016)

This commit is contained in:
boojack
2023-02-03 10:30:18 +08:00
committed by GitHub
parent 2d14047c73
commit 1ace332152
7 changed files with 146 additions and 24 deletions

View File

@@ -1,10 +1,12 @@
package main
import (
"net/http"
"os"
"os/signal"
"syscall"
_ "github.com/mattn/go-sqlite3"
"github.com/pkg/errors"
"context"
"fmt"
@@ -24,11 +26,11 @@ const (
`
)
func run() error {
ctx := context.Background()
func main() {
profile, err := profile.GetProfile()
if err != nil {
return err
fmt.Printf("failed to get profile, error: %+v\n", err)
return
}
println("---")
println("profile")
@@ -38,19 +40,35 @@ func run() error {
println("version:", profile.Version)
println("---")
serverInstance, err := server.NewServer(ctx, profile)
ctx, cancel := context.WithCancel(context.Background())
s, err := server.NewServer(ctx, profile)
if err != nil {
return errors.Wrap(err, "failed to start server")
cancel()
fmt.Printf("failed to create server, error: %+v\n", err)
return
}
c := make(chan os.Signal, 1)
// Trigger graceful shutdown on SIGINT or SIGTERM.
// The default signal sent by the `kill` command is SIGTERM,
// which is taken as the graceful shutdown signal for many systems, eg., Kubernetes, Gunicorn.
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
go func() {
sig := <-c
fmt.Printf("%s received.\n", sig.String())
s.Shutdown(ctx)
cancel()
}()
println(greetingBanner)
fmt.Printf("Version %s has started at :%d\n", profile.Version, profile.Port)
return serverInstance.Start(ctx)
}
func main() {
if err := run(); err != nil {
fmt.Printf("error: %+v\n", err)
os.Exit(1)
if err := s.Start(ctx); err != nil {
if err != http.ErrServerClosed {
fmt.Printf("failed to start server, error: %+v\n", err)
cancel()
}
}
// Wait for CTRL-C.
<-ctx.Done()
}