Skip to content

Commit

Permalink
feat(runner): implement graceful shutdown
Browse files Browse the repository at this point in the history
  • Loading branch information
dwisiswant0 committed Jul 11, 2023
1 parent 7a73857 commit 6e0fb27
Showing 1 changed file with 26 additions and 2 deletions.
28 changes: 26 additions & 2 deletions internal/runner/runner.go
Original file line number Diff line number Diff line change
@@ -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"
Expand All @@ -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
}

0 comments on commit 6e0fb27

Please sign in to comment.