dongou2019 2017-01-11 15:01
浏览 98
已采纳

如何与http.ListenAndServe结合使用defer?

When using http.ListenAndServe() in Go, this results in a blocking situation where the application, apparently, can only be stopped by killing it. This seems to skip processing my defer statements. Please see the code below. When I kill the application the db is not closed. How can I make sure my defer statement will be run?

func main() {
  db := NewDB(DBFILENAME)
  defer db.Close()
  http.HandleFunc("/", handler)
  http.ListenAndServe(":80", nil)
}
  • 写回答

2条回答 默认 最新

  • drze7794 2017-01-11 15:08
    关注

    defer statements get executed only when the function enclosing them returns. Your main function is not returning when you kill it. So you need to use signals and channels.

    This is a good link explaining the same https://www.socketloop.com/tutorials/golang-intercept-ctrl-c-interrupt-or-kill-signal-and-determine-the-signal-type .

    I faced the same problem with my last project. I implemented a similar solution in my project wshare .

    In your case, you can try something like

         ch := make(chan os.Signal, 3)
    
         signal.Notify(ch, os.Interrupt,syscall.SIGTERM,syscall.SIGINT)
    
    
         go func() {
                 signalType := <-ch
                 signal.Stop(ch)
                 log.Println("Exit command received. Exiting...")
    
                 // this is a good place to flush everything to disk
                 // before terminating.
                 db.Close()
                 log.Println("Signal type : ", signalType)
    
                 os.Exit(0)
    
         }()
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码