From a9c2e2468d250f81283ae8454b06b2d92d6ac56e Mon Sep 17 00:00:00 2001 From: kucherenkovova Date: Thu, 13 Jun 2024 22:32:24 +0300 Subject: [PATCH] [xnet/xhttp] fix goroutine leak (#5) --- xnet/xhttp/README.md | 2 +- xnet/xhttp/server.go | 10 ++++++++-- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/xnet/xhttp/README.md b/xnet/xhttp/README.md index b62c4c7..4171400 100644 --- a/xnet/xhttp/README.md +++ b/xnet/xhttp/README.md @@ -3,5 +3,5 @@ Extensions to the standard Go library's `net/http` package. `ListenAndServe` alt ### Install ``` -go get github.com/kucherenkovova/gopypaste/xnet/xhttp@v0.1.1 +go get github.com/kucherenkovova/gopypaste/xnet/xhttp@v0.1.2 ``` diff --git a/xnet/xhttp/server.go b/xnet/xhttp/server.go index d512793..839b37f 100644 --- a/xnet/xhttp/server.go +++ b/xnet/xhttp/server.go @@ -14,13 +14,19 @@ func ListenAndServeContext(ctx context.Context, addr string, handler http.Handle defer cancel() server := &http.Server{Addr: addr, Handler: handler} + done := make(chan struct{}) go func() { - <-ctx.Done() - _ = server.Shutdown(context.Background()) + select { + case <-ctx.Done(): + _ = server.Shutdown(context.Background()) + case <-done: + return + } }() if err := server.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { + close(done) return err }