我試圖使用超時的上下文來退出長時間運行的 http GET 請求。對 url 的請求應該超過 10 秒,但我的請求在 2 秒后沒有超時。問題是什么?傳遞給 makeGet() 函數的 ctx 來自 http handlefun r.Contex()。 makeGet(ctx context.Context, url string, respBuffer *bytes.Buffer) (int, error){ req, err := http.NewRequest(http.MethodGet, url, nil) if err != nil { return 0, err } // ctx, cancel := context.WithTimeout(ctx, time.Second*2) defer cancel() req.WithContext(ctx) req.Header.Set("Content-Type", "application/json") client := &http.Client{} resp, err := client.Do(req) if err != nil { return 0, err } defer resp.Body.Close() _, err = respBuffer.ReadFrom(resp.Body) if err != nil { return resp.StatusCode, err } }
1 回答

富國滬深
TA貢獻1790條經驗 獲得超9個贊
總結以下評論中的答案:
原始代碼的問題:req.WithContext(ctx)
沒有根據請求設置上下文,但它返回一個新請求,該請求上設置了上下文。
可以使用新請求來解決該問題req = req.WithContext(ctx)
,使用或者直接使用返回值Client.Do
來執行查詢Client.Do(req.WithContext(ctx))
- 1 回答
- 0 關注
- 181 瀏覽
添加回答
舉報
0/150
提交
取消