dsewbh5588 2018-08-23 00: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-23 00: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:

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

报告相同问题?

悬赏问题

  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)