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



请帮助我理解*请求。上下文功能:

// 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()
}
  1. 为什么我们需要这个函数而不是在*请求上使用公共属性?它只是为了封装,所以没有人可以改变它,使它有效地只读吗?

  2. 什么时候可以返回r.ctx != nilcontext.Background()?难道不是每个http请求在被接收的那一刻就保证有一个上下文吗?context.Background()的用途是什么,如果它永远不会成为"完成"由于超时或取消?基本上,为什么不这样做呢?

func (r *Request) Context() context.Context {
return r.ctx
}
  1. 是的,它是用于封装的。使用WithContext或NewReqeustWithContext来创建一个带有您选择的上下文的请求。

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

最新更新