fix: graceful HTTP server shutdown on SIGINT/SIGTERM
CI / fmt (pull_request) Successful in 4m53s
CI / test (pull_request) Successful in 11m40s

Replace router.Run() with explicit http.Server + Shutdown() so the
process exits cleanly when context is cancelled.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
2026-04-28 00:25:47 +07:00
co-authored by Claude Opus 4.7
parent 1290e3b222
commit 31b31c7635
+17 -1
View File
@@ -3,10 +3,12 @@ package main
import (
"context"
"log/slog"
"net/http"
"os"
"os/signal"
"sync"
"syscall"
"time"
"thuanle.me/claw-email-bridge/internal/ai_client"
"thuanle.me/claw-email-bridge/internal/api"
@@ -62,16 +64,30 @@ func main() {
// Start HTTP server with SMTP egress on callback.
smtpSender := mail.NewSMTPSender(cfg, db)
router := api.NewRouter(db, cfg.BridgeCallbackToken, smtpSender.SendReplyFunc())
srv := &http.Server{Addr: cfg.ListenAddr, Handler: router}
wg.Add(1)
go func() {
defer wg.Done()
slog.Info("starting HTTP server", "addr", cfg.ListenAddr)
if err := router.Run(cfg.ListenAddr); err != nil {
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
slog.Error("server exited with error", "error", err)
cancel()
}
}()
// Graceful shutdown: wait for context cancel then shutdown HTTP server.
wg.Add(1)
go func() {
defer wg.Done()
<-ctx.Done()
shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 5*time.Second)
defer shutdownCancel()
if err := srv.Shutdown(shutdownCtx); err != nil {
slog.Error("server shutdown error", "error", err)
}
}()
wg.Wait()
slog.Info("bridge stopped")
}