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 多电路系统共用电源的串扰问题
  • ¥15 shape_predictor_68_face_landmarks.dat
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料