duanguai2781 2015-09-09 04:12
浏览 871
已采纳

无论如何,在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.
        //
}
  • 写回答

1条回答 默认 最新

  • doulan6150 2015-09-09 05:13
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)