I am using the Mux library from Gorilla Web Toolkit along with the bundled Go http server.
The problem is that in my application the HTTP server is only one component and it is required to stop and start at my discretion.
When I call http.ListenAndServe(fmt.Sprintf(":%d", service.Port()), service.router)
it blocks and I cannot seem to stop the server from running.
I am aware this has been a problem in the past, is that still the case? Are there any new solutions please? Thanks.
You can close the server by closing its context.
And whenever you are ready to close it, call:
I was figuring the same question so I decided to write it all down to a Github tutorial. Checkout the full source code, integration test and how to implement an SSL layer for protection!
If anyone would like to contribute to it, make it even better, write more tests, feel free to submit a PR!
Contributions and knowledge sharing is more than welcome!
Go 1.8 will include graceful and forceful shutdown, available via
Server::Shutdown(context.Context)
andServer::Close()
respectively.The relevant commit can be found here
You can construct
net.Listener
which you can
Close()
and
http.Serve()
on itAs mentioned in
yo.ian.g
's answer. Go 1.8 has included this functionality in the standard lib.Minimal example for for
Go 1.8+
:Original Answer - Pre Go 1.8 :
Building on Uvelichitel's answer.
You can create your own version of
ListenAndServe
which returns anio.Closer
and does not block.Full code available here.
The HTTP Server will close with the error
accept tcp [::]:8080: use of closed network connection
Since none of the previous answers say why you can't do it if you use http.ListenAndServe(), I went into the v1.8 http source code and here is what it says:
As you can see the http.ListenAndServe function does not return the server variable. This means you cannot get to 'server' to use the Shutdown command. Therefore, you need to create your own 'server' instance instead of using this function for the graceful shutdown to be implemented.
Regarding graceful shutdown (introduced in Go 1.8), a bit more concrete example: