From 6e0fb2745eb1003122c019c8bb86d82c39a3fb07 Mon Sep 17 00:00:00 2001 From: Dwi Siswanto Date: Tue, 11 Jul 2023 08:37:33 +0700 Subject: [PATCH] feat(runner): implement graceful shutdown --- internal/runner/runner.go | 28 ++++++++++++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/internal/runner/runner.go b/internal/runner/runner.go index 87cf7e3..7c79a9a 100644 --- a/internal/runner/runner.go +++ b/internal/runner/runner.go @@ -1,9 +1,13 @@ package runner import ( + "context" "fmt" + "os" + "time" "net/http" + "os/signal" "github.com/charmbracelet/log" "github.com/kitabisa/teler-proxy/common" @@ -26,7 +30,27 @@ func New(opt *common.Options) error { ErrorLog: logger, } - log.Info("Server started", "port", opt.Port) + sig := make(chan os.Signal, 1) + signal.Notify(sig, os.Interrupt) - return server.ListenAndServe() + go func() { + <-sig + log.Warn("Interuppted. Shutting down...") + + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + + if err := server.Shutdown(ctx); err != nil { + log.Fatal("Server shutdown error", "error", err) + } + }() + + log.Info("Server started", "port", opt.Port, "pid", os.Getpid()) + + err = server.ListenAndServe() + if err != nil && err != http.ErrServerClosed { + return err + } + + return nil }