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)

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中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号