在 Go 中,如何有效地将流式 http 响应主体写入文件中的查找位置?

In Go, how do I write a streaming http response body to a seek position in a file effectively?

我有一个程序可以组合多个 http 响应并写入文件中的相应搜索位置。我目前正在

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)

由于 ioutil.ReadAll,这有时会导致大量内存使用。

我试过 bytes.Buffer 作为

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

但还是老样子。

我的意图是对文件使用缓冲写入,然后再次寻找偏移量,并再次继续写入直到接收到流的末尾(因此从 buf.ReadFrom 捕获偏移值) .但它也将所有内容保存在内存中并立即写入。

将类似流直接写入磁盘而不将整个内容保存在缓冲区中的最佳方法是什么?

非常感谢一个例子来理解。

谢谢。

使用io.Copy将响应正文复制到文件:

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