2017-06-29 60 views
1

我有一個自定義的http客戶端,它有一個默認的超時值。該代碼是這樣的:我可以檢查一個上下文是否已經超時設置?

type Client struct { 
    *http.Client 
    timeout time.Duration 
} 

func (c *Client) Send(ctx context.Context, r *http.Request) (int, []byte, error) { 
    // If ctx has timeout set, then don't change it. 
    // Otherwise, create new context with ctx.WithTimeout(c.timeout) 
} 

我如何檢查是否已ctx超時設置或不?

回答

2

檢查從context.Deadline的布爾值返回:

截止日期返回時代表此背景下 執行的工作時間應被取消。如果沒有截止日期爲 ,則截止日期返回ok == false。對Deadline的連續調用返回相同的結果。

func (c *Client) Send(ctx context.Context, r *http.Request) (int, []byte, error) { 
    if _, deadlineSet := ctx.Deadline(); !deadlineSet { 
     ctx, _ = context.WithTimeout(ctx, c.timeout) 
    } 
} 
相關問題