登录
首页 >  Golang >  Go问答

如何检查请求是否被取消

来源:Golang技术栈

时间:2023-04-19 19:07:35 250浏览 收藏

学习知识要善于思考,思考,再思考!今天golang学习网小编就给大家带来《如何检查请求是否被取消》,以下内容主要包含golang等知识点,如果你正在学习或准备学习Golang,就都不要错过本文啦~让我们一起来看看吧,能帮助到你就更好了!

问题内容

我有这个简单的代码,我在其中尝试检查请求是否被取消。但令人惊讶的是,它打印false而不是true在 go 1.9 中。

我想知道检查的正确方法是什么?

package main

import (
    "context"
    "log"
    "net/http"
)

func main() {
    r, _ := http.NewRequest("GET", "http://example.com", nil)
    ctx, cancel := context.WithCancel(context.Background())
    r = r.WithContext(ctx)
    ch := make(chan bool)
    go func() {
        _, err := http.DefaultClient.Do(r)
        log.Println(err == context.Canceled)
        ch 

正确答案

在 Go 1.13+ 中最简洁的方法是使用新errors.Is函数。

// Create a context that is already canceled
ctx, cancel := context.WithCancel(context.Background())
cancel()

// Create the request with it
r, _ := http.NewRequestWithContext(ctx, "GET", "http://example.com", nil)

// Do it, it will immediately fail because the context is canceled.
_, err := http.DefaultClient.Do(r)
log.Println(err) // Get http://example.com: context canceled

// This prints false, because the http client wraps the context.Canceled
// error into another one with extra information.
log.Println(err == context.Canceled)

// This prints true, because errors.Is checks all the errors in the wrap chain,
// and returns true if any of them matches.
log.Println(errors.Is(err, context.Canceled))

终于介绍完啦!小伙伴们,这篇关于《如何检查请求是否被取消》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

声明:本文转载于:Golang技术栈 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>