dongwupu5991 2017-11-30 09:53
浏览 539
已采纳

如何在Gin框架中添加after回调

I need to quit the application with os.Exit(0) AFTER HTTP request has finished completely. My application asks another server if it needs an upgrade, so I need to quit for performing a self upgrade with a reboot, but I don't want to break current HTTP request.

When I try to quit in middleware after c.Next() or at the end of handler function, the browser gives error: localhost didn’t send any data.

How this can be done?

  • 写回答

2条回答 默认 最新

  • dongqiang2024 2017-12-03 16:34
    关注

    As you say, your program is terminating before the HTTP connection completes cleanly - you need to wait for the HTTP transaction to finish and then exit. Fortunately since Go 1.8 http.Server has a Shutdown method that does what you need.

    Shutdown gracefully shuts down the server without interrupting any active connections. Shutdown works by first closing all open listeners, then closing all idle connections, and then waiting indefinitely for connections to return to idle and then shut down.

    So, the general approach would be:

    exitChan := make(chan struct{})
    
    // Get a reference to exitChan to your handlers somehow
    
    h := &http.Server{
        // your config
    }
    go func(){
        h.ListenAndServe() // Run server in goroutine so as not to block
    }()
    
    <-exitChan // Block on channel
    h.Shutdown(nil) // Shutdown cleanly with a timeout of 5 seconds
    

    And then exitChan <- struct{}{} in your handler/middleware when shutdown is required.

    See also: How to stop http.ListenAndServe()

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集