为了账号安全,请及时绑定邮箱和手机立即绑定

为什么 *Request.Context() 存在并在某些情况下返回

为什么 *Request.Context() 存在并在某些情况下返回

Go
ibeautiful 2022-10-10 10:32:00
请帮助我理解 *Request.Context 函数:// Context returns the request's context. To change the context, use// WithContext.//// The returned context is always non-nil; it defaults to the// background context.//// For outgoing client requests, the context controls cancellation.//// For incoming server requests, the context is canceled when the// client's connection closes, the request is canceled (with HTTP/2),// or when the ServeHTTP method returns.func (r *Request) Context() context.Context {    if r.ctx != nil {        return r.ctx    }    return context.Background()}为什么我们需要这个函数而不是在 *Request 上使用公共属性?它只是为了封装,以便没有人可以更改它,使其有效地只读吗?什么时候会返回r.ctx != niland context.Background()?不是每个http请求都保证在收到它的那一刻就有一个上下文吗?context.Background()如果由于超时或取消而永远不会“完成”,那有什么用?基本上,为什么不这样做呢?func (r *Request) Context() context.Context {    return r.ctx}
查看完整描述

1 回答

?
缥缈止盈

TA贡献2041条经验 获得超4个赞

  1. 是的,它是用于封装的。使用WithContextNewReqeustWithContext使用您选择的上下文创建请求。

  2. r := &http.Request{}创建一个没有上下文的请求。确保非零返回值对调用者来说是一种方便。当没有指定其他上下文时,背景上下文是一个合适的默认值。


查看完整回答
反对 回复 2022-10-10
  • 1 回答
  • 0 关注
  • 70 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信