io.Copy导致golang内存不足

时间:2014-04-23 04:28:42

标签: go

我使用io.Copy()来复制一个大约700Mb的文件,但它导致内存不足

bodyBuf := &bytes.Buffer{}
bodyWriter := multipart.NewWriter(bodyBuf)

//key step
fileWriter, err := bodyWriter.CreateFormFile(paramName, fileName)
if err != nil {
    return nil, err
}

file, err := os.Open(fileName) //the file size is about 700Mb
if err != nil {
    return nil, err
}
defer file.Close()

//iocopy
copyLen, err := io.Copy(fileWriter, file) // this cause out of memory
if err != nil {
    fmt.Println("io.copy(): ", err)

    return nil, err
}

错误消息如下:

runtime: memory allocated by OS (0x752cf000) not in usable range [0x18700000,0x98700000)
runtime: out of memory: cannot allocate 1080229888-byte block (1081212928 in use)
fatal error: out of memory

我为buf分配了足够的内存,导致bodyWriter.CreateFormFile()中的内存不足

buf := make([]byte, 766509056)
bodyBuf := bytes.NewBuffer(buf)
bodyWriter := multipart.NewWriter(bodyBuf)

fileWriter, err := bodyWriter.CreateFormFile(paramName, fileName) // out of memory
if err != nil {
    return nil, err
}

1 个答案:

答案 0 :(得分:7)

那是因为你'复制'到bodyBuf,这是一个内存缓冲区,迫使Go尝试分配一个与整个文件一样大的内存块。

根据您对multipart的使用,您似乎试图通过http流式传输文件?在这种情况下,请不要将bytes.Buffer传递给multipart.NewWriter,而是直接传递您的http连接。