go - 我可以检查上下文是否已经设置了超时吗?

标签 go

我有一个自定义的 http 客户端,它有一个默认的超时值。代码是这样的:

type Client struct {
  *http.Client
  timeout time.Duration
}

func (c *Client) Send(ctx context.Context, r *http.Request) (int, []byte, error) {
  // If ctx has timeout set, then don't change it.
  // Otherwise, create new context with ctx.WithTimeout(c.timeout)
}

如何检查 ctx 是否设置了超时?

最佳答案

检查 context.Deadline 的 bool 返回值:

Deadline returns the time when work done on behalf of this context should be canceled. Deadline returns ok==false when no deadline is set. Successive calls to Deadline return the same results.

Deadline() (deadline time.Time, ok bool)
func (c *Client) Send(ctx context.Context, r *http.Request) (int, []byte, error) {
    if _, deadlineSet := ctx.Deadline(); !deadlineSet {
        ctx, _ = context.WithTimeout(ctx, c.timeout)
    }
}

关于go - 我可以检查上下文是否已经设置了超时吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44822381/

相关文章:

go - 在 for 循环中使用函数中的变量 - Golang

dictionary - 如何在Golang中使用与 map 中的键相同的数据来区分两种自定义结构类型?

go - 替换 viper map 键而不替换整个 map

go - 检查准备就绪的同步 channel

go - 具有错误行为的模拟功能仍然通过

go - 无法使用默认服务帐户和谷歌云库从谷歌 Kubernetes 引擎访问谷歌云存储

algorithm - 转到 : longest common subsequence to print result array

json - Golang JSON 到包含 slice 的 map 本身的 map slice (无类型)

go - 如何部署带有自定义go构建约束/标签的golang谷歌云功能?

go - 数据存储不会将嵌套结构放入 Go