請幫我理解 *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 != nilandcontext.Background()?不是每個 http 請求在收到時都保證有背景關系嗎?而什么用的context.Background(),如果它永遠不會成為“完成”由于超時或取消?基本上,為什么不這樣做呢?
func (r *Request) Context() context.Context {
return r.ctx
}
uj5u.com熱心網友回復:
是的,它是為了封裝。使用WithContext或NewReqeustWithContext創建具有您選擇的背景關系的請求。
r := &http.Request{}創建一個沒有背景關系的請求。確保非 nil 回傳值對呼叫者來說很方便。當沒有指定其他背景關系時,背景背景關系是合適的默認值。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/330777.html
