For a http ‘listenAndServe’ and ‘listener.close’, then it will trigger listener with this err “use of closed network connection”
I linked the issue, and there are example codes. I’m not sure how to solve this err in an elegant way.
Can someone help?
opened 05:06AM - 22 Apr 22 UTC
closed 07:00AM - 22 Apr 22 UTC
<!--
Please answer these questions before submitting your issue. Thanks!
-->
…
### What version of Go are you using (`go version`)?
<pre>
go 1.18.0
</pre>
### Source codes
```shell
package main
import (
"net"
"net/http"
"time"
)
func main() {
listener, err := net.Listen("tcp", net.JoinHostPort("0.0.0.0", "0"))
if nil!=err{
panic(err)
}
httpServer := &http.Server{}
go func() {
err :=httpServer.Serve(listener)
if nil!=err && err!=http.ErrServerClosed && err!=net.ErrClosed{
panic(err)
}
}()
time.Sleep(time.Second)
err = listener.Close()
if nil!=err{
panic(err)
}
time.Sleep(time.Second)
}
```
### Error
```shell
panic: accept tcp [::]:64309: use of closed network connection
goroutine 6 [running]:
main.main.func1()
.../main.go:19 +0xb3
created by main.main
.../main.go:16 +0x15a
exit status 2
```
### Question:
Is that a right situation with this panic? Why I close the listener the server got one error that not belong 'http.ErrServerClosed' ?
And What is the right way to handle this error?
apmattil
(Ari Mattila)
April 23, 2022, 7:04pm
2
your main control flow will first start the server (in separate go routine).
Then it will close the socket (calling listener.Close()) the server is serving.
look waitgroup examples how to wait for other go routines to finnish.
system
(system)
Closed
July 22, 2022, 7:04pm
3
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.