在Go中通过HTTP接收二进制数据

cmh*_*bbs 1 api rest binary binary-data go

在go中通过HTTP接收二进制数据的最佳方法是什么?就我而言,我想将zip文件发送到我的应用程序的REST API.goweb特有的例子很棒,但net/http也很好.

Ela*_*ich 12

只需从请求正文中读取它

就像是

package main

import ("fmt";"net/http";"io/ioutil";"log")

func h(w http.ResponseWriter, req *http.Request) {
    buf, err := ioutil.ReadAll(req.Body)
    if err!=nil {log.Fatal("request",err)}
    fmt.Println(buf) // do whatever you want with the binary file buf
}
Run Code Online (Sandbox Code Playgroud)

更合理的方法是将文件复制到某个流中

defer req.Body.Close()
f, err := os.TempFile("", "my_app_prefix")
if err!=nil {log.Fatal("cannot open temp file", err)}
defer f.Close()
io.Copy(f, req.Body)
Run Code Online (Sandbox Code Playgroud)

  • 请注意,这种特殊的处理方式会将整个请求正文读取到内存中。在现实世界中,您可能希望限制大小、将数据存储在磁盘上或其他方式。 (2认同)