Skip to content

Commit 33cbf23

Browse files
fix(server): eliminate send-on-closed-channel race in StartHTTPServer (#708)
Fix a data race in StartHTTPServer where the shutdown goroutine calls close(errCh) concurrently with the listener goroutine sending to errCh, producing a "send on closed channel" panic.
1 parent c6dfc7e commit 33cbf23

1 file changed

Lines changed: 8 additions & 4 deletions

File tree

internal/application/server.go

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import (
77
"net/http"
88
"os"
99
"os/signal"
10+
"sync"
1011
"syscall"
1112
"time"
1213

@@ -39,13 +40,15 @@ func StartHTTPServer(
3940
}
4041
}
4142

42-
errCh := make(chan error)
43+
errCh := make(chan error, 1)
4344

4445
// Create a channel to listen for signals
4546
sigCh := make(chan os.Signal, 1)
4647
signal.Notify(sigCh, syscall.SIGTERM)
4748

48-
go func() {
49+
var wg sync.WaitGroup
50+
51+
wg.Go(func() {
4952
var err error
5053
loggers.Infof("Starting server listening on port %d\n", port)
5154
if tlsEnabled {
@@ -61,7 +64,7 @@ func StartHTTPServer(
6164
if err != nil && err != http.ErrServerClosed {
6265
errCh <- err
6366
}
64-
}()
67+
})
6568

6669
// Handle graceful shutdown in a separate goroutine
6770
go func() {
@@ -83,7 +86,8 @@ func StartHTTPServer(
8386
} else {
8487
loggers.Info("Server gracefully stopped")
8588
}
86-
close(errCh) // Close the error channel after shutdown
89+
wg.Wait()
90+
close(errCh)
8791
}()
8892

8993
return srv, errCh

0 commit comments

Comments
 (0)