3

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.
        //
}
fannheyward
  • 18,599
  • 12
  • 71
  • 109

1 Answers1

5

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

Community
  • 1
  • 1
icza
  • 389,944
  • 63
  • 907
  • 827