Skip to content

Commit 4ad21a0

Browse files
committed
Improve concurrent server error handling
Replace error channel with proper exit coordination and error collection to handle errors from both HTTP and HTTPS servers gracefully.
1 parent d81723f commit 4ad21a0

1 file changed

Lines changed: 20 additions & 5 deletions

File tree

pkg/mcp-proxy/main.go

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package mcpproxy
33
import (
44
"context"
55
"crypto/sha256"
6+
"errors"
67
"fmt"
78
"net/http"
89
"net/url"
@@ -152,7 +153,7 @@ func Run(
152153
},
153154
}
154155

155-
errCh := make(chan error)
156+
exit := make(chan struct{})
156157
var wg sync.WaitGroup
157158

158159
httpServer := &http.Server{
@@ -173,18 +174,32 @@ func Run(
173174
}
174175

175176
wg.Add(2)
177+
errs := []error{}
178+
lock := sync.Mutex{}
176179
go func() {
177180
defer wg.Done()
178-
errCh <- httpServer.ListenAndServe()
181+
err := httpServer.ListenAndServe()
182+
if err != nil {
183+
lock.Lock()
184+
errs = append(errs, err)
185+
lock.Unlock()
186+
}
187+
exit <- struct{}{}
179188
}()
180189

181190
go func() {
182191
defer wg.Done()
183-
errCh <- httpsServer.ListenAndServeTLS("", "")
192+
err := httpsServer.ListenAndServeTLS("", "")
193+
if err != nil {
194+
lock.Lock()
195+
errs = append(errs, err)
196+
lock.Unlock()
197+
}
198+
exit <- struct{}{}
184199
}()
185200

186201
logger.Info("Starting server", zap.Strings("listen", []string{listen, listenTLS}))
187-
err := <-errCh
202+
<-exit
188203
shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 5*time.Second)
189204
defer shutdownCancel()
190205
if shutdownErr := httpServer.Shutdown(shutdownCtx); shutdownErr != nil {
@@ -193,7 +208,7 @@ func Run(
193208
if shutdownErr := httpsServer.Shutdown(shutdownCtx); shutdownErr != nil {
194209
logger.Warn("HTTPS server shutdown error", zap.Error(shutdownErr))
195210
}
196-
return err
211+
return errors.Join(errs...)
197212
} else {
198213
logger.Info("Starting server", zap.String("listen", listen))
199214
return router.Run(listen)

0 commit comments

Comments
 (0)