Is there anyway to close client request in golang/gin?

为君一笑 提交于 2020-01-05 17:57:09

问题


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:


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: Goroutine execution inside an http handler



来源:https://stackoverflow.com/questions/32470792/is-there-anyway-to-close-client-request-in-golang-gin

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!