登录
首页 >  Golang >  Go问答

http put 服务器处理大文件

来源:stackoverflow

时间:2024-03-06 21:57:27 292浏览 收藏

哈喽!今天心血来潮给大家带来了《http put 服务器处理大文件》,想必大家应该对Golang都不陌生吧,那么阅读本文就都不会很困难,以下内容主要涉及到,若是你正在学习Golang,千万别错过这篇文章~希望能帮助到你!

问题内容

请考虑此处发布的这段代码,它处理 http put 请求。对于小文件,它工作正常:

$ curl  -v http://192.168.1.10:9193/ -t red.tx
*   trying 192.168.1.10...
* connected to 192.168.1.10 (192.168.1.10) port 9193 (#0)
> put /red.tx http/1.1
> host: 192.168.1.10:9193
> user-agent: curl/7.47.0
> accept: */*
> content-length: 19697247
> expect: 100-continue
>
< http/1.1 100 continue
* we are completely uploaded and fine
< http/1.1 200 ok
< date: fri, 26 jul 2019 00:43:43 gmt
< content-length: 0
< content-type: text/plain; charset=utf-8
<
* connection #0 to host 192.168.1.10 left intact

但是 - 发送一个大于 1g 的大文件,它会耗尽内存。可以理解的是,由于整个正文被读入为 contents, err := ioutil.readall(r.body)

runtime: out of memory: cannot allocate 536870912-byte block (537919488 in use)
fatal error: out of memory    
runtime stack:
runtime.throw(0x259a35, 0xd)
        /usr/lib/go-1.7/src/runtime/panic.go:566 +0x78
runtime.largeAlloc(0x1ffffe00, 0x10616f01, 0x10637afc)
        /usr/lib/go-1.7/src/runtime/malloc.go:776 +0xc8
runtime.mallocgc.func1()
        /usr/lib/go-1.7/src/runtime/malloc.go:669 +0x34
runtime.systemstack(0x10aa8200)
        /usr/lib/go-1.7/src/runtime/asm_arm.s:247 +0x80
runtime.mstart()
        /usr/lib/go-1.7/src/runtime/proc.go:1079

请告诉我从 r.body 读取并将其写入文件的正确方法。谢谢!


解决方案


尝试将请求负载直接复制到文件中。

f, err := os.Create(temporaryFilename)
if err != nil {
    return err
}
defer f.Close()

_, err := io.Copy(f, r.Body)

如果您需要对复制的文件执行某些操作,只需操作创建的文件对象(在上面的示例中为 f)。

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《http put 服务器处理大文件》文章吧,也可关注golang学习网公众号了解相关技术文章。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>