go - 如何在 Gin 框架中添加后回调

标签 go go-gin

在 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{}{}在需要关闭时在您的处理程序/中间件中。

另请参阅:How to stop http.ListenAndServe()

关于go - 如何在 Gin 框架中添加后回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47570449/

相关文章:

go - 将文件复制到文件夹中,直到达到一定大小

go - golang bigquery文档指定完成操作符,但生成编译错误

rest - 如何使用 Golang 实现导入数据功能?

go - 为什么 post 请求在 gin golang 中不起作用?

reactjs - axios.post请求获取404

go - 如何为静态文件设置http header ?

json - Golang/Gin-gonic : Force POST headers to JSON

go - 如何在golang中间接传递接口(interface)

pointers - Go循环指针变化

go - Golang 可以在虚拟机上运行吗?