dongxu2398
2016-06-18 16:33
浏览 645
已采纳

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

I am using an http client to get a json body, and read it to a byte array like

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
}

In the above code, GetJobJson.Body is of type io.ReadCloser, which implements Reader, having Read method, which I am using here as

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

But since I am handling error here, it is returning an error which says EOF.

The http endpoint to where I am sending the request is running an apache server, mentioning it here since I am not sure if it matters.

If I am not handling the error, I get the complete json body, which is there in the remote server, and the program continues to work as expected.

What is the best way to handle this? Is the Read method that I use, is bad for this situation? Please advise.

Thank you.

图片转代码服务由CSDN问答提供 功能建议

我正在使用http客户端获取json正文,并将其读取为类似字节数组

  client:= new(http.Client)
client.Timeout = time.Second * 10 
GetJobJson,err:= client.Get(joblocation.String())//其中的工作位置是 类型为* url.Url 
if err!= nil {
 errorlog.Err.Println(“从作业中获取错误”,joblocation.String(),err)
返回false,http.StatusBadRequest,nil 
} \  nbuff:= make([] byte,GetJobJson.ContentLength)
length,err:= GetJobJson.Body.Read(buff)//这将返回EOF错误
if err!= nil {
 errorlog.Err.Println(“ 读取长度为”的请求正文时出错,长度为“ vs contentlength”,GetJobJson.ContentLength,err)
返回false,http.StatusBadRequest,nil 
} 
   
 
 

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

  length,err:= GetJo  bJson.Body.Read(buff)
   
 
 

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

我向其发送请求的http终结点正在运行apache服务器,在此提及它是因为我不确定是否重要。

如果我没有处理该错误,则将获取完整的json主体,该主体位于远程服务器中,并且程序将继续按预期运行。

处理此问题的最佳方法是什么? 我使用的 Read 方法对这种情况不利吗? 请提出建议。

谢谢。

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dorpbn1027 2016-06-18 19:01
    已采纳

    Handing io.EOF is part of the contract of using an io.Reader, and it indicates that there's nothing more to read. If you have read what you expected to read, there is no error. If you look at functions like ioutil.ReadAll, you'll see that it handles the EOF, and returns no error at the end of the stream.

    You may also consider not checking for ContentLength, as it precludes you from handing chunked responses.

    点赞 打赏 评论