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 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀