-5

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?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Marco
  • 4,817
  • 5
  • 34
  • 75
  • 3
    Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it **in the question itself**. – Adrian Jun 13 '19 at 18:24

1 Answers1

-1

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:

http.ListenAndServe() is blocking by definition and therefore will not run any code after that line.

Marco
  • 4,817
  • 5
  • 34
  • 75