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

无论如何,在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

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

报告相同问题?

悬赏问题

  • ¥50 微信聊天记录备份到电脑提示成功了,但还是没同步到电脑微信
  • ¥15 python怎么在已有视频文件后添加新帧
  • ¥20 虚幻UE引擎如何让多个同一个蓝图的NPC执行一样的动画,
  • ¥15 fluent里模拟降膜反应的UDF编写
  • ¥15 MYSQL 多表拼接link
  • ¥15 关于某款2.13寸墨水屏的问题
  • ¥15 obsidian的中文层级自动编号
  • ¥15 同一个网口一个电脑连接有网,另一个电脑连接没网
  • ¥15 神经网络模型一直不能上GPU
  • ¥20 wpf datagrid单元闪烁效果失灵