dongwen6743 2018-11-15 15:49
浏览 206
已采纳

如果失去连接,golang gin停止处理程序将如何立即起作用

I am using gin-gonic/gin to write my server.

It seems even if the connection is lost, the handler function is still running. For example, if I visit http://127.0.0.1:8080/ping and close the browser suddenly, the screen will continue to print all the numbers.

package main

import (
    "github.com/gin-gonic/gin"
    "log"
    "time"
)

func main() {
    r := gin.Default()
    r.GET("/ping", func(c *gin.Context) {
        for i := 1; i < 15; i++ {
            time.Sleep(time.Second * 1)
            log.Println(i)
        }
        c.JSON(200, gin.H{
            "message": "pong",
        })
    })
    r.Run("127.0.0.1:8080")
}

How should I stop handler function immediately (e.g. to reduce server load)?

  • 写回答

1条回答 默认 最新

  • douguan3470 2018-11-15 16:06
    关注

    The request context is canceled when the client disconnects, so simply check if c.Done() is ready to receive:

    package main
    
    import (
        "log"
        "time"
    
        "github.com/gin-gonic/gin"
    )
    
    func main() {
        r := gin.Default()
        r.GET("/ping", func(c *gin.Context) {
            t := time.NewTicker(1 * time.Second)
            defer t.Stop()
    
            for i := 1; i < 15; i++ {
                select {
                case <-t.C:
                    log.Println(i)
                case <-c.Request.Context().Done():
                    // client gave up
                    return
                }
            }
    
            c.JSON(200, gin.H{
                "message": "pong",
            })
        })
        r.Run("127.0.0.1:8080")
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 vmware exsi重置后的密码
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥15 电磁场的matlab仿真
  • ¥15 mars2d在vue3中的引入问题
  • ¥50 h5唤醒支付宝并跳转至向小荷包转账界面