@@ -143,28 +143,6 @@ func (c *Connection) Close() error {
143143 c .onceClose .Do (func () {
144144 // Close doneChan to signify that we're shutting down
145145 close (c .doneChan )
146- // Gracefully stop the muxer
147- if c .muxer != nil {
148- c .muxer .Stop ()
149- }
150- // Wait for other goroutines to finish
151- c .waitGroup .Wait ()
152- // Close channels
153- close (c .errorChan )
154- close (c .protoErrorChan )
155- // We can only close a channel once, so we have to jump through a few hoops
156- select {
157- // The channel is either closed or has an item pending
158- case _ , ok := <- c .handshakeFinishedChan :
159- // We successfully retrieved an item
160- // This will probably never happen, but it doesn't hurt to cover this case
161- if ok {
162- close (c .handshakeFinishedChan )
163- }
164- // The channel is open and has no pending items
165- default :
166- close (c .handshakeFinishedChan )
167- }
168146 })
169147 return err
170148}
@@ -214,9 +192,41 @@ func (c *Connection) TxSubmission() *txsubmission.TxSubmission {
214192 return c .txSubmission
215193}
216194
195+ // shutdown performs cleanup operations when the connection is shutdown, either due to explicit Close() or an error
196+ func (c * Connection ) shutdown () {
197+ // Gracefully stop the muxer
198+ if c .muxer != nil {
199+ c .muxer .Stop ()
200+ }
201+ // Wait for other goroutines to finish
202+ c .waitGroup .Wait ()
203+ // Close channels
204+ close (c .errorChan )
205+ close (c .protoErrorChan )
206+ // We can only close a channel once, so we have to jump through a few hoops
207+ select {
208+ // The channel is either closed or has an item pending
209+ case _ , ok := <- c .handshakeFinishedChan :
210+ // We successfully retrieved an item
211+ // This will probably never happen, but it doesn't hurt to cover this case
212+ if ok {
213+ close (c .handshakeFinishedChan )
214+ }
215+ // The channel is open and has no pending items
216+ default :
217+ close (c .handshakeFinishedChan )
218+ }
219+ }
220+
217221// setupConnection establishes the muxer, configures and starts the handshake process, and initializes
218222// the appropriate mini-protocols
219223func (c * Connection ) setupConnection () error {
224+ // Start Goroutine to shutdown when doneChan is closed
225+ go func () {
226+ <- c .doneChan
227+ c .shutdown ()
228+ }()
229+ // Create muxer instance
220230 c .muxer = muxer .New (c .conn )
221231 // Start Goroutine to pass along errors from the muxer
222232 c .waitGroup .Add (1 )
0 commit comments