Home > Mobile >  Why *Request.Context() exists and returns a context.Background() in some cases?
Why *Request.Context() exists and returns a context.Background() in some cases?

Time:10-21

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()
}
  1. 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?

  2. When can it happen that the r.ctx != nil and context.Background() is returned? Isn't every http request guaranteed to have a context the moment it is received? And what is the use of context.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:

  1. Yes, it is for encapsulation. Use WithContext or NewReqeustWithContext to create a request with the context of your choice.

  2. 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.

  • Related