首页 > 后端开发 > Golang > 正文

Golang 函数:用 Deadline 设定上下文截止时间

王林
发布: 2024-10-05 22:51:02
原创
324人浏览过

Go 函数中,Deadline 可为上下文设定截止时间,防止无限期阻塞和资源泄露。使用 context.WithDeadline() 函数设定 Deadline:设定 5 秒截止时间的上下文:ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(5*time.Second))实战案例:防止 HTTP 请求无限期阻塞:// 创建 5 秒截止时间的上下文 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(5*time.Second)) // 发起 HTTP 请求,设置上下文 req, _ := http.NewRequest(http.MethodGet, "https://example.com", nil)

golang 函数:用 deadline 设定上下文截止时间

Go 函数:用 Deadline 设定上下文截止时间

在 Go 中,Deadline 允许对上下文设定截止时间,这可以防止无限期阻塞和资源泄露。本文将介绍如何使用 Deadline 以及提供一个实战案例。

使用 Deadline

要为上下文设定 Deadline,可以使用 context.WithDeadline() 函数:

立即学习go语言免费学习笔记(深入)”;

import (
    "context"
    "time"
)

// 创建一个有 5 秒截止时间的上下文
ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(5*time.Second))
登录后复制

实战案例:HTTP 请求超时

考虑一个使用 net/http 发起 HTTP 请求的程序。为了防止请求无限期阻塞,我们可以使用 Deadline:

import (
    "context"
    "fmt"
    "net/http"
    "time"
)

func main() {
    // 创建一个有 5 秒截止时间的上下文
    ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(5*time.Second))
    defer cancel()

    // 发起 HTTP 请求并设置上下文
    req, _ := http.NewRequest(http.MethodGet, "https://example.com", nil)
    req = req.WithContext(ctx)
    res, err := http.DefaultClient.Do(req)
    if err != nil {
        fmt.Println(err)
        return
    }

    fmt.Println(res)
}
登录后复制

如果请求在 5 秒内没有完成,上下文将超时并返回一个 context.DeadlineExceeded 错误。

以上就是Golang 函数:用 Deadline 设定上下文截止时间的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
相关标签:
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号