Go 取消请求

Go 取消请求,go,go-gin,Go,Go Gin,如果连接在10秒钟之前关闭,如何取消进一步处理 有c.Request.Context().Done(),但找不到如何使用它的示例 func main() { r := gin.Default() r.GET("/ping", func(c *gin.Context) { time.Sleep(10 * time.Second) // or some db operation log.Print("Processing&

如果连接在10秒钟之前关闭,如何取消进一步处理

c.Request.Context().Done()
,但找不到如何使用它的示例

func main() {
    r := gin.Default()
    r.GET("/ping", func(c *gin.Context) {
        time.Sleep(10 * time.Second) // or some db operation
        log.Print("Processing")
        c.JSON(200, gin.H{
            "message": "pong",
        })
    })
    r.Run()
}

您可以异步运行长时间运行的操作,并让它在一个通道上发送完成信号

然后在完成通道上阻塞,并使用
select
语句执行
c.Request.Context().Done()

func main() {
    r := gin.Default()
    r.GET("/ping", func(c *gin.Context) {
        signal := make(chan struct{}, 1)

        go longRunningOperation(signal)

        select {
            case <-signal:
                close(signal) // remember to clean up after yourself
                // move on, will print "Processing"
    
            case <-c.Request.Context().Done():
                // abort
                return
        }

        log.Print("Processing")
        c.JSON(200, gin.H{
            "message": "pong",
        })
    })
    r.Run()
}


func longRunningOperation(signal chan<- struct{}) {
    time.Sleep(10 * time.Second)
    signal <- struct{}{} // signal that this operation has finished
}

你想取消哪一部分?您的意思是停止服务器还是只显示响应http消息?假设请求被取消,则不使用http响应响应该请求。或者阻止打印<代码>处理<代码>(在示例中)。所以,如果处理速度慢,并且达到超时连接时间(此处为10秒),您想停止处理吗?
func Handler(c *gin.Context) {
    signal := make(chan struct{}, 1)
    go longRunningOperation(c.Request.Context(), signal)
    ...
}

func longRunningOperation(ctx context.Context, signal chan<- struct{}) {
    if err := doSomethingContext(ctx); err != nil {
        return
    }
    signal <- struct{}{} // signal that this operation has finished (successfully)
}