HTTP 请求,JSON,重用连接

HTTP Requests, JSON, reusing connections

我正在使用 Go 通过 HTTPS 发出许多请求,但我遇到了无法重用连接和 运行 端口不足的问题。我提出的请求是 API returns 格式的 JSON 数据,然后我将其 json.Decode 转换为 Go 值。

根据我在本网站上遇到的问题 (#1, #2), in order for Go to reuse the connection for another request, I must read the entirety of the response's body before closing (note this wasn't always the behavior, as stated here)。

Previously the HTTP client's (*Response).Body.Close would try to keep
reading until EOF, hoping to reuse the keep-alive HTTP connection...

在典型情况下,我会使用前面链接中显示的示例,如下所示:

ioutil.ReadAll(resp.Body)

但是因为我通过这样的代码从 JSON 中提取数据:

...

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)

我不确定这两种方法如何相互作用。

所以问题是,我如何确保已读取整个响应,以便稍后可以将连接重新用于另一个请求?

如果只想使用解码器解码单个对象,那么可以使用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)
}

您也可以在每次调用时延迟复制,但这样您可以更轻松地处理或记录意外数据或错误。