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条)

报告相同问题?

悬赏问题

  • ¥15 宇视监控服务器无法登录
  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)