Закрывать listener API, если сервер не стартовал после его открытия

This commit is contained in:
2026-11-05 14:41:26 +03:00
parent 8e8e567fef
commit 99216ef808
2 changed files with 29 additions and 4 deletions
+1
View File
@@ -64,6 +64,7 @@ func run(ctx context.Context, log *slog.Logger, cfg config.Config, alias string)
if err != nil { if err != nil {
return fmt.Errorf("listen on %s: %w", cfg.Addr(), err) return fmt.Errorf("listen on %s: %w", cfg.Addr(), err)
} }
defer ln.Close()
log.Info("starting", "env", cfg.Env, "addr", cfg.Addr(), log.Info("starting", "env", cfg.Env, "addr", cfg.Addr(),
"gomaxprocs", runtime.GOMAXPROCS(0), "db_max_conns", cfg.DBMaxConns, "gomaxprocs", runtime.GOMAXPROCS(0), "db_max_conns", cfg.DBMaxConns,
"drain_delay", cfg.DrainDelay.String(), "shutdown_timeout", cfg.ShutdownTimeout.String(), "drain_delay", cfg.DrainDelay.String(), "shutdown_timeout", cfg.ShutdownTimeout.String(),
+28 -4
View File
@@ -40,6 +40,31 @@ func TestMain(m *testing.M) {
// A start-up failure after the background work began must still end the // A start-up failure after the background work began must still end the
// process with an error, not leave it waiting for a signal. // process with an error, not leave it waiting for a signal.
func TestRunFailsFastWhenTheDebugListenerCannotStart(t *testing.T) { func TestRunFailsFastWhenTheDebugListenerCannotStart(t *testing.T) {
if err := runWithBusyDebugAddr(t, 0); err == nil {
t.Fatal("run succeeded on a busy debug address")
}
}
func TestFailedStartReleasesTheAPIPort(t *testing.T) {
probe, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
port := probe.Addr().(*net.TCPAddr).Port
probe.Close()
if err := runWithBusyDebugAddr(t, port); err == nil {
t.Fatal("run succeeded on a busy debug address")
}
ln, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", port))
if err != nil {
t.Fatalf("the API port is still taken after the failed start: %v", err)
}
ln.Close()
}
func runWithBusyDebugAddr(t *testing.T, port int) error {
t.Helper()
busy, err := net.Listen("tcp", "127.0.0.1:0") busy, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
@@ -47,7 +72,7 @@ func TestRunFailsFastWhenTheDebugListenerCannotStart(t *testing.T) {
defer busy.Close() defer busy.Close()
cfg := config.Config{ cfg := config.Config{
Host: "127.0.0.1", Host: "127.0.0.1",
Port: 0, Port: port,
ShutdownTimeout: time.Second, ShutdownTimeout: time.Second,
MaxBodyBytes: 1024, MaxBodyBytes: 1024,
DatabaseURL: db.DSN, DatabaseURL: db.DSN,
@@ -63,10 +88,9 @@ func TestRunFailsFastWhenTheDebugListenerCannotStart(t *testing.T) {
}() }()
select { select {
case err := <-done: case err := <-done:
if err == nil { return err
t.Fatal("run succeeded on a busy debug address")
}
case <-time.After(10 * time.Second): case <-time.After(10 * time.Second):
t.Fatal("run hung instead of returning the listen error") t.Fatal("run hung instead of returning the listen error")
return nil
} }
} }