英文:
Receiving binary data via HTTP in Go
问题
什么是在go中通过HTTP接收二进制数据的最佳方法?在我的情况下,我想将一个zip文件发送到我的应用程序的REST API。特定于goweb的示例会很好,但net/http也可以。
英文:
What's the best way to go about receiving binary data via HTTP in go? In my case, I'd like to send a zip file to my application's REST API. Examples specific to goweb would be great, but net/http is fine too.
答案1
得分: 20
只读取请求体中的内容
类似于
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) // 对二进制文件 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)
英文:
Just read it from the request body
Something like
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
}
A more reasonable approach is to copy the file into some stream
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论