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

在Go中,如何有效地将流式http响应主体写入文件中的seek位置?,http,go,io,httpresponse,Http,Go,Io,Httpresponse,我有一个程序,它组合了多个http响应,并将其写入一个文件上相应的seek位置。我目前正在做这件事 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 /

我有一个程序,它组合了多个http响应,并将其写入一个文件上相应的seek位置。我目前正在做这件事

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
as

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

我的意图是使用缓冲写入文件,然后再次查找偏移量,并继续再次写入,直到收到流的结尾(从而从buf.ReadFrom捕获偏移量值)。但它同时也在记忆中保留着一切,并同时写作

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

如果能举个例子来理解,我们将不胜感激

谢谢。

用于将响应正文复制到文件:

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

如果您可以在读取响应正文之前获取
someval
:只需从正文中读取
someval
多个字节并忽略它们,然后读取其余的字节,或者直接将其复制到文件中。谢谢@Volker,我在第二种情况下使用bytes.Buffer尝试读取
someval
多个字节,这显然是没有发生,因为我不知道如何正确地做。如果您的意思是使用http
range
头读取几个字节,然后反复执行,那么我正在访问的http端点有一个连接限制,这限制了我在我的端点的goroutine中生成过多连接,按顺序执行会很耗时。