在 HTTP 请求完全完成后,我需要使用 os.Exit(0)
退出应用程序。我的应用程序询问另一台服务器是否需要升级,因此我需要退出以通过重启执行 self 升级,但我不想中断当前的 HTTP 请求。
当我尝试在 c.Next()
之后或在处理函数结束时退出中间件时,浏览器给出错误:localhost 没有发送任何数据
.
如何做到这一点?
最佳答案
如您所说,您的程序在 HTTP 连接完全完成之前终止 - 您需要等待 HTTP 事务完成然后退出。幸运的是,自 Go 1.8 http.Server
有一个 Shutdown
method那就是你需要的。
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.
所以,一般的做法是:
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
然后 exitChan <- struct{}{}
在需要关闭时在您的处理程序/中间件中。
关于go - 如何在 Gin 框架中添加后回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47570449/