dsewbh5588 2018-08-22 16:22
浏览 267
已采纳

将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条回答 默认 最新

  • dpwo36915 2018-08-22 16:35
    关注

    http.Response.Body is of type io.ReadCloser, which can only be read once (as you can see it does not have a method to rewind).

    So alternatively for decoding purposes you could read your just created file.

    Or if the response is not large (or you could trim it with io.LimitReader) - you can read it into a buffer

    (not tested, something along these lines):

    f, err := os.Create("./response.json")
    if err != nil {
        log.Fatal(err)
    }
    defer f.Close()
    
    var buf bytes.Buffer
    tee := io.TeeReader(r.Body, &buf)
    
    io.Copy(f, tee)
    
    var result JSONResult
    if err := json.NewDecoder(buf).Decode(&result); err != nil {
        log.Fatal(err)
    }
    

    References:

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

悬赏问题

  • ¥15 编译python程序为pyd文件报错:{"source code string cannot contain null bytes"
  • ¥20 关于#r语言#的问题:广义加行模型拟合曲线后如何求拐点
  • ¥15 fluent设置了自动保存后,会有几个时间点不保存
  • ¥20 激光照射到四象线探测器,通过液晶屏显示X、Y值
  • ¥15 这怎么做,怎么在我的思路下改下我这写的不对
  • ¥50 数据库开发问题求解答
  • ¥15 安装anaconda时报错
  • ¥15 小程序有个导出到插件方式,我是在分包下引入的插件,这个export的路径对吗,我看官方文档上写的是相对路径
  • ¥20 希望有人能帮我完成这个设计( *ˊᵕˋ)
  • ¥100 将Intptr传入SetHdevmode()将Intptr传入后转换为DEVMODE的值与外部代码不一致
手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部