无论如何,有没有办法在 golang/gin 中关闭客户端请求?

fan*_*ard 3 go go-gin

使用gin框架。

是否有办法通知客户端关闭请求连接,然后服务器处理程序可以执行任何后台作业而不让客户端等待连接?

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

icz*_*cza 6

是的,你可以这么做。只需从处理程序返回即可。而你想要做的后台工作,你应该把它放在一个新的 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... 
    }()
}
Run Code Online (Sandbox Code Playgroud)

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