简体   繁体   中英

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

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.
        //
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM