請幫助我理解 *Request.Context 函數(shù):// 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()}為什么我們需要這個函數(shù)而不是在 *Request 上使用公共屬性?它只是為了封裝,以便沒有人可以更改它,使其有效地只讀嗎?什么時候會返回r.ctx != niland context.Background()?不是每個http請求都保證在收到它的那一刻就有一個上下文嗎?context.Background()如果由于超時或取消而永遠不會“完成”,那有什么用?基本上,為什么不這樣做呢?func (r *Request) Context() context.Context { return r.ctx}
為什么 *Request.Context() 存在并在某些情況下返回
ibeautiful
2022-10-10 10:32:00