登录
首页 >  Golang >  Go问答

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

来源:stackoverflow

时间:2024-02-12 16:33:22 391浏览 收藏

本篇文章给大家分享《为什么 *Request.Context() 存在并在某些情况下返回 context.Background() ?》,覆盖了Golang的常见基础知识,其实一个语言的全部知识点一篇文章是不可能说完的,但希望通过这些问题,让读者对自己的掌握程度有一定的认识(B 数),从而弥补自己的不足,更好的掌握它。

问题内容

请帮助我理解 *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()
}
  1. 为什么我们需要这个函数而不是在 *request 上使用公共属性?难道只是为了封装,这样没人可以改变它,使其实际上是只读的吗?

  2. 什么时候会出现 r.ctx != nilcontext.background() 被返回?不是每个 http 请求在收到时都保证有一个上下文吗?如果 context.background() 由于超时或取消而永远不会变为“完成”,那么它有什么用?基本上,为什么不这样做呢?

func (r *Request) Context() context.Context {
    return r.ctx
}

正确答案


  1. 是的,是为了封装。使用 WithContextNewReqeustWithContext 根据您选择的上下文创建请求。

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

好了,本文到此结束,带大家了解了《为什么 *Request.Context() 存在并在某些情况下返回 context.Background() ?》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>