我有一個程序,它結合了多個 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 somevalfs.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 捕獲偏移值)。但它也將所有內容都保存在內存中并立即寫入。將類似流直接寫入磁盤而不將整個內容保存在緩沖區中的最佳方法是什么?一個可以理解的例子將不勝感激。謝謝你。
1 回答

繁星coding
TA貢獻1797條經驗 獲得超4個贊
使用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
- 1 回答
- 0 關注
- 211 瀏覽
添加回答
舉報
0/150
提交
取消