我正在使用 Go 通過 HTTPS 發(fā)出許多請求,但我遇到了不重用連接和端口用完的問題。我向 API 發(fā)出請求,該 API 以 JSON 格式返回數(shù)據(jù),然后將其json.Decode轉換為 Go 值。根據(jù)我在這個網(wǎng)站上遇到的問題(#1,#2),為了讓 Go 重用連接來處理另一個請求,我必須在關閉之前閱讀整個響應正文(注意這并不總是行為,說這里)。Previously the HTTP client's (*Response).Body.Close would try to keepreading until EOF, hoping to reuse the keep-alive HTTP connection...在典型的情況下,我會使用前面鏈接中顯示的示例,如下所示:ioutil.ReadAll(resp.Body)但因為我是通過這樣的代碼從 JSON 中提取數(shù)據(jù):...req, _ := http.NewRequest("GET", urlString, nil)req.Header.Add("Connection", "keep-alive")resp, err = client.Do(req)defer resp.Body.Close()...decoder := json.NewDecoder(resp.Body)decoder.Decode(data)我不確定這兩種方法將如何交互。所以問題是,如何確保已讀取整個響應,以便稍后可以將連接重用于另一個請求?
1 回答

胡子哥哥
TA貢獻1825條經(jīng)驗 獲得超6個贊
如果您只想使用 Decoder 解碼單個對象,那么您可以使用該More()方法查看流中是否還有更多需要讀取的對象。
decoder := json.NewDecoder(resp.Body)
err := decoder.Decode(data)
if err != nil {
// handle err
}
if decoder.More() {
// there's more data in the stream, so discard whatever is left
io.Copy(ioutil.Discard, resp.Body)
}
您也可以在每次調用時推遲復制,但如果有意外數(shù)據(jù)或錯誤,您可以更輕松地處理或記錄。
- 1 回答
- 0 關注
- 186 瀏覽
添加回答
舉報
0/150
提交
取消