I have previously blogged about creating a webserver in Go with graceful shutdown.
https://marcofranssen.nl/go-webserver-with-gracefull-shutdown/#TLDR
This solution works perfectly, however for a bigger project I would like to further structure the code.
I have refactored this code as in the following gist.
https://gist.github.com/marcofranssen/699c1aa97c8a33ab20b5eccada275b08
For some reason the line with srv.ListenAndServe() doesn't seem to be executed while the graceful shutdown still runs in a go routine like before.
To me the code looks identical, just refactored into separate files and added a Start function.
Can anyone explain me why it doesn't execute until I give the Interrupt signal, causing the http server to start and shutdown immediately?
I found the answer with the help of a fellow Gopher from the community.
The line of code containing
srv.ListenAndServe()is a blocking line of code causing the log after this line of code not to happen.In my original code I demonstrated in my earlier blog I had this log in front of the line with
srv.ListenAndServe(). Therefore in that example the same code was logging to console as expected.So after all it was a silly mistake which you can easily read over many times. Basically 2 lines of code where swapped and I forgot about the blocking behavior of
http.ListenAndServe().KEY takeaway: