Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Fix server shutdown logic #100

Merged
merged 2 commits into from
Apr 6, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 21 additions & 15 deletions typing-server/api/cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,18 +76,21 @@ func main() {
} else {
logger.Info("シードデータは挿入されませんでした")
}

// WaitGroupの宣言
var wg sync.WaitGroup

// エラーを通知するためのチャネル
errChan := make(chan error, 1)

// シグナルハンドリングの準備
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)

// HTTPサーバーの非同期起動
wg.Add(1)
go func() {
defer wg.Done() // 関数終了時にWaitGroupをデクリメント

// サーバーの設定
// ルーティングの設定
r := router.SetupRouter()
Expand All @@ -97,29 +100,32 @@ func main() {
Addr: ":8080",
Handler: r,
}

// 非同期でサーバーを開始
go func() {
logger.Info("server is running at Addr :8080")
if err := server.ListenAndServe(); err != http.ErrServerClosed {
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
logger.Error("failed to listen and serve: %v", err)
errChan <- err // エラーをチャネルに送信
}
}()
// シグナルを待機
<-sigChan
logger.Info("shutting down the server...")
ctx := context.TODO() // Use context.TODO() as a temporary placeholder
if err := server.Shutdown(ctx); err != nil {
logger.Error("error during server shutdown: %v", err)
errChan <- err // エラーをチャネルに送信

// エラーまたはシグナルを待機
select {
case err := <-errChan:
logger.Error("server stopped due to an error: %v", err)
case sig := <-sigChan:
logger.Info("received signal: %v", sig)
// グレースフルシャットダウン
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := server.Shutdown(ctx); err != nil {
logger.Error("error during server shutdown: %v", err)
errChan <- err // エラーをチャネルに送信
}
}
}()
select {
case <-errChan: // エラーが発生した場合
logger.Error("server stopped due to an error")
case sig := <-sigChan: // シグナルを受信した場合
logger.Info("received signal: %s", sig)
}

wg.Wait() // HTTPサーバーの終了を待機
close(errChan)
logger.Info("server exited")
Expand Down
Loading