dpvmtdu364462 2016-05-31 11:39
浏览 309
已采纳

在Go中,如何有效地将流式HTTP响应正文写入文件中的搜索位置?

I have a program that combines multiple http responses and writes to the respective seek positions on a file. I am currently doing this by

client := new(http.Client)
req, _ := http.NewRequest("GET", os.Args[1], nil)
resp, _ := client.Do(req)
defer resp.Close()
reader, _ := ioutil.ReadAll(resp.Body) //Reads the entire response to memory
//Some func that gets the seek value someval
fs.Seek(int64(someval), 0)
fs.Write(reader)

This sometimes results in a large memory usage because of the ioutil.ReadAll.

I tried bytes.Buffer as

buf := new(bytes.Buffer)
offset, _ := buf.ReadFrom(resp.Body) //Still reads the entire response to memory.
fs.Write(buf.Bytes())

but it was still the same.

My intention was to use a buffered write to the file, then seek to the offset again, and to continue write again till the end of stream is received (and hence capturing the offset value from buf.ReadFrom). But it was also keeping everything in the memory and writing at once.

What is the best way to write a similar stream directly to the disk, without keeping the entire content in buffer?

An example to understand would be much appreciated.

Thank you.

  • 写回答

1条回答 默认 最新

  • douzang7928 2016-05-31 12:06
    关注

    Use io.Copy to copy the response body to the file:

    resp, _ := client.Do(req)
    defer resp.Close()
    //Some func that gets the seek value someval
    fs.Seek(int64(someval), 0)
    n, err := io.Copy(fs, resp.Body)
    // n is number of bytes copied
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#lua#的问题,请各位专家解答!
  • ¥15 什么设备可以研究OFDM的60GHz毫米波信道模型
  • ¥15 不知道是该怎么引用多个函数片段
  • ¥30 关于用python写支付宝扫码付异步通知收不到的问题
  • ¥50 vue组件中无法正确接收并处理axios请求
  • ¥15 隐藏系统界面pdf的打印、下载按钮
  • ¥15 基于pso参数优化的LightGBM分类模型
  • ¥15 安装Paddleocr时报错无法解决
  • ¥15 python中transformers可以正常下载,但是没有办法使用pipeline
  • ¥50 分布式追踪trace异常问题