Golang shuts down listener network
I am having trouble closing the listener so that I can reopen it on the same port. I am writing a proxy that is hot configured - what it does (redirects / blocks, etc) can be configured on the fly. The proxy server works in a routine. The problem I am facing is that when I reconfigured the listener and proxy, the listener is still using that port from the previous configuration. (FYI listener is a global pointer) I am trying something like:
to kill the listener:
func KillProxy() {
if listener != nil {
log.Println(" *** TRYING TO STOP THE PROXY SERVER")
(*listener).Close()
listener = nil
}
}
before reconfiguring it like this:
log.Println("listener (S1): ", listener)
if listener == nil {
// Start the listener to listen on the connection.
l, err := net.Listen(CONN_TYPE, CONN_HOST + ":" + CONN_PORT)
if err != nil {
log.Println("error here: ", err)
}
listener = &l //set it as a pointer to the newly created listener
}
log.Println("listener (S2): ", listener)
however, it doesn't seem to work - I get the error:
listener (S1):
here: listen tcp 0.0.0.0:8080: bind: address is already in use
listener (S2): 0xc2080015e0
and then a massive stack trace that adds up to:
panic: runtime error: invalid memory address or pointer spread to zero
CHANGE ANSWER TO JIM:
Interesting re-pointers. OK. I am not working while waiting for the socket to close, I am not sure how this should be done. The proxy library I'm using is this: https://github.com/abourget/goproxy . Things happen:
KillProxy() refreshProxy()
refreshProxy stores the above code that tries to repurpose the listener. The last thing that happens in refreshProxy()
:
go http.Serve(*listener, proxy)
So, if I return to the listener as a global variable rather than a pointer, I can do KillProxy ():
func KillProxy() {
if listener != nil {
listener.Close()
listener = nil
}
}
and then set up the listener again like
listener, err := net.Listen(CONN_TYPE, CONN_HOST + ":" + CONN_PORT)
if err != nil {
log.Println("error here: ", err)
}
However, I don't know how to wait and check if the socket is closed before trying to create a listener object?
source to share
Ok, this is far from perfect, but the only way I found the error, that I am not wrong, was to artificially put a delay in my code so that the socket could close. This is not very convenient as it means the proxy goes down for 2 seconds while the socket is closed, but at least it doesn't throw an error. If anyone has a better solution, I'd love to hear it.
func KillProxy() {
if listener != nil {
listener.Close()
log.Println("waiting for socket to close")
time.Sleep(2 * time.Second)
}
}
source to share