sco*_*ott 3 io http httpresponse go
我有一个程序,它结合了多个 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)
Run Code Online (Sandbox Code Playgroud)
这有时会导致大量内存使用,因为ioutil.ReadAll.
我想bytes.Buffer作为
buf := new(bytes.Buffer)
offset, _ := buf.ReadFrom(resp.Body) //Still reads the entire response to memory.
fs.Write(buf.Bytes())
Run Code Online (Sandbox Code Playgroud)
但还是一样。
我的意图是使用缓冲写入文件,然后再次寻找偏移量,并再次继续写入直到收到流的结尾(从而从 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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1447 次 |
| 最近记录: |