dqask02082 2019-06-13 18:13
浏览 96

Web服务器正常关闭无法正常工作

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?

  • 写回答

1条回答 默认 最新

  • doushang1778 2019-06-13 18:30
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染