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

请帮助我理解 *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

}


ibeautiful
浏览 71回答 1
1回答

缥缈止盈

是的,它是用于封装的。使用WithContext或NewReqeustWithContext使用您选择的上下文创建请求。r := &http.Request{}创建一个没有上下文的请求。确保非零返回值对调用者来说是一种方便。当没有指定其他上下文时,背景上下文是一个合适的默认值。
打开App,查看更多内容
随时随地看视频慕课网APP