英文:
Is there anyway to close client request in golang/gin?
问题
使用gin框架。
有没有办法通知客户端关闭请求连接,然后服务器处理程序可以在不让客户端等待连接的情况下执行后台任务?
func Test(c *gin.Context) {
c.String(200, "ok")
// 关闭客户端请求,然后执行一些任务,例如与远程服务器同步数据。
//
}
英文:
Using gin framework.
Is there anyway to notify client to close request connection, then server handler can do any back-ground jobs without letting the clients to wait on the connection?
func Test(c *gin.Context) {
c.String(200, "ok")
// close client request, then do some jobs, for example sync data with remote server.
//
}
答案1
得分: 5
是的,你可以这样做。只需从处理程序中返回即可。而你想要执行的后台任务,应该将其放在一个新的 goroutine 中。
请注意,连接和/或请求可能会被放回到连接池中,但这是无关紧要的,客户端将看到请求的处理已结束。你可以实现你想要的效果。
代码示例:
func Test(c *gin.Context) {
c.String(200, "ok")
// 通过从该函数返回,响应将发送给客户端
// 并且与客户端的连接将被关闭
// 启动的 goroutine 将继续执行:
go func() {
// 这个函数将继续执行...
}()
}
另请参阅:https://stackoverflow.com/questions/31116870/goroutine-execution-inside-an-http-handler
英文:
Yes, you can do that. By simply returning from the handler. And the background job you want to do, you should put that on a new goroutine.
Note that the connection and/or request may be put back into a pool, but that is irrelevant, the client will see that serving the request ended. You achieve what you want.
Something like this:
func Test(c *gin.Context) {
c.String(200, "ok")
// By returning from this function, response will be sent to the client
// and the connection to the client will be closed
// Started goroutine will live on, of course:
go func() {
// This function will continue to execute...
}()
}
Also see: https://stackoverflow.com/questions/31116870/goroutine-execution-inside-an-http-handler
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论