Please help me to understand the *Request.Context function:
// 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()
}
Why do we need this function instead of using a public property on *Request? Is it just for encapsulation so that nobody can change it, making it effectively read-only?
When can it happen that the
r.ctx != nil
andcontext.Background()
is returned? Isn't every http request guaranteed to have a context the moment it is received? And what is the use ofcontext.Background()
if it never becomes 'done' due to timeout or cancellation? Basically, why not this instead?
func (r *Request) Context() context.Context {
return r.ctx
}
CodePudding user response:
Yes, it is for encapsulation. Use WithContext or NewReqeustWithContext to create a request with the context of your choice.
r := &http.Request{}
creates a request with no context. Ensuring a non-nil return value is a convenience for the caller. The background context is a suitable default when no other context is specified.