在go中通过HTTP接收二进制数据的最佳方式是什么?在我的例子中,我想发送一个zip文件到我的应用程序的REST API。特定于goweb的例子会很棒,但net/http也很好。
发布于 2012-07-30 14:59:03
只需从请求正文中读取它
就像这样
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
}一种更合理的方法是将文件复制到某个流中
defer req.Body.Close()
f, err := ioutil.TempFile("", "my_app_prefix")
if err!=nil {log.Fatal("cannot open temp file", err)}
defer f.Close()
io.Copy(f, req.Body)https://stackoverflow.com/questions/11714912
复制相似问题