使用 http.Client.Get 方法和 Body.Read() 方法处理时导致终止的 EOF 错误

EOF error causing termination when handled in using http.Client.Get method and Body.Read() method

我正在使用 http 客户端获取 json 主体,并将其读取为字节数组,如

client := new(http.Client)
client.Timeout = time.Second * 10
GetJobJson, err := client.Get(joblocation.String()) //where joblocation is of type *url.Url
if err != nil {
    errorlog.Err.Println("Error getting job from", joblocation.String(), err)
    return false, http.StatusBadRequest, nil
}
buff := make([]byte, GetJobJson.ContentLength)
length, err := GetJobJson.Body.Read(buff) //This returns an EOF error
if err != nil {
    errorlog.Err.Println("Error reading request body of length", length, "vs contentlength", GetJobJson.ContentLength, err)
    return false, http.StatusBadRequest, nil
}

在上面的代码中,GetJobJson.Body是类型io.ReadCloser,它实现了Reader,具有Read方法,我在这里使用

]
length, err := GetJobJson.Body.Read(buff) 

但是由于我在这里处理错误,它返回了一个 EOF 错误。

我发送请求的 http 端点是 运行 一个 apache 服务器,在这里提到它是因为我不确定它是否重要。

如果我不处理错误,我会得到完整的 json 正文,它在远程服务器中,程序继续按预期工作。

处理此问题的最佳方法是什么?我使用的 Read 方法是否适合这种情况?

Handing io.EOF 是使用 io.Reader 合同的一部分,它表示没有更多内容可读。如果您已经阅读了您期望阅读的内容,则没有错误。如果您查看像 ioutil.ReadAll 这样的函数,您会发现它处理 EOF,并且 returns 在流的末尾没有错误。

您也可以考虑不检查 ContentLength,因为它会阻止您处理分块响应。