dsewbh5588
2018-08-23 00:22
浏览 217
已采纳

将HTTP响应正文写入文件后,出现EOF错误[重复]

This question already has an answer here:

I'd like to save a JSON response to a text file before parsing it:

req, err := http.NewRequest("POST", url, body)
req.Header.Set("Authorization", "secret_key")
req.Header.Set("Content-Type", "application/json")

resp, err := client.Do(req)
if err != nil {
    log.Fatal(err)
}
defer resp.Body.Close()

f, err := os.Create("./response.json")
if err != nil {
    log.Fatal(err)
}
defer f.Close()
io.Copy(f, resp.Body)

var result JSONResult
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
    log.Fatal(err)
}

It successfully writes the JSON to a file but then fails on the decoding step with an error that just says EOF. If I parse before writing to file it parses ok, but then the file is empty. Can someone please explain what's happening here? Thanks!

</div>
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

相关推荐 更多相似问题