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() 函数:
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 错误。

