From d58b409a096c6a4700237c9926b4cf2c119c25a8 Mon Sep 17 00:00:00 2001 From: Leo Antunes Date: Wed, 9 Feb 2022 22:26:56 +0100 Subject: [PATCH] do not propagate "use of closed conn" error if expected There's unfortunately no way (AFAIK) of actively interrupting a net.Listener.Accept() call, so we have to deal with it erroring out when its net.Listener is closed. Unfortunately(2) there's also no better way of matching the low-level error than string checks, since it is not exported by the stdlib. --- cmux.go | 9 +++++++++ cmux_test.go | 2 +- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/cmux.go b/cmux.go index 5ba921e..63142fa 100644 --- a/cmux.go +++ b/cmux.go @@ -19,6 +19,7 @@ import ( "fmt" "io" "net" + "strings" "sync" "time" ) @@ -169,6 +170,14 @@ func (m *cMux) Serve() error { for { c, err := m.root.Accept() if err != nil { + if strings.Contains(err.Error(), "use of closed network connection") { + select { + case <-m.donec: // error is expected + return nil + default: + } + } + if !m.handleErr(err) { return err } diff --git a/cmux_test.go b/cmux_test.go index 7b3cfb7..b0af1db 100644 --- a/cmux_test.go +++ b/cmux_test.go @@ -47,7 +47,7 @@ const ( ) func safeServe(errCh chan<- error, muxl CMux) { - if err := muxl.Serve(); !strings.Contains(err.Error(), "use of closed") { + if err := muxl.Serve(); err != nil && !strings.Contains(err.Error(), "use of closed") { errCh <- err } }