fix(server): propagate shutdown error, http timeouts, ctx-aware migrate

This commit is contained in:
2026-04-29 11:52:27 +08:00
parent fc0724fc0b
commit 0f9c7fa657
3 changed files with 32 additions and 11 deletions
+8 -4
View File
@@ -51,7 +51,7 @@ func New(ctx context.Context, cfg *config.Config, dist embed.FS) (*App, error) {
log := logger.FromEnv(cfg.Env, nil)
// 跑 migrations 必须在开池前;否则首次启动连不存在的表会让 ping 失败。
if err := db.Migrate(cfg.DB.DSN, "file://migrations"); err != nil {
if err := db.Migrate(ctx, cfg.DB.DSN, "file://migrations"); err != nil {
return nil, fmt.Errorf("migrate: %w", err)
}
@@ -109,6 +109,9 @@ func New(ctx context.Context, cfg *config.Config, dist embed.FS) (*App, error) {
Addr: cfg.HTTP.Addr,
Handler: r,
ReadHeaderTimeout: 10 * time.Second,
ReadTimeout: 30 * time.Second,
WriteTimeout: 60 * time.Second,
IdleTimeout: 120 * time.Second,
}
return &App{cfg: cfg, log: log, pool: pool, server: srv}, nil
}
@@ -130,11 +133,12 @@ func (a *App) Run(ctx context.Context) error {
a.log.Info("shutdown signal received, draining...")
shutCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
if err := a.server.Shutdown(shutCtx); err != nil {
a.log.Error("server shutdown", "err", err.Error())
shutErr := a.server.Shutdown(shutCtx)
if shutErr != nil {
a.log.Error("server shutdown", "err", shutErr.Error())
}
a.pool.Close()
return nil
return shutErr
case err := <-errCh:
a.pool.Close()
return err