1

使用gin框架。

无论如何通知客户端关闭请求连接,然后服务器处理程序可以在不让客户端等待连接的情况下执行任何后台作业?

func Test(c *gin.Context) {
        c.String(200, "ok")
        // close client request, then do some jobs, for example sync data with remote server.
        //
}
4

1 回答 1

3

是的,你可以这么做。通过简单地从处理程序返回。而你想做的后台工作,你应该把它放在一个新的 goroutine 上。

请注意,连接和/或请求可能会被放回池中,但这无关紧要,客户端将看到服务请求已结束。你实现你想要的。

像这样的东西:

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... 
    }()
}

另请参阅:http 处理程序中的 Goroutine 执行

于 2015-09-09T05:13:56.833 回答