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语言免费学习笔记(深入)”;
大小仅1兆左右 ,足够轻便的商城系统; 易部署,上传空间即可用,安全,稳定; 容易操作,登陆后台就可设置装饰网站; 并且使用异步技术处理网站数据,表现更具美感。 前台呈现页面,兼容主流浏览器,DIV+CSS页面设计; 如果您有一定的网页设计基础,还可以进行简易的样式修改,二次开发, 发布新样式,调整网站结构,只需修改css目录中的css.css文件即可。 商城网站完全独立,网站源码随时可供您下载
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 错误。









