通过Go语言接收HTTP中的二进制数据

huangapple go评论88阅读模式
英文:

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)

huangapple
  • 本文由 发表于 2012年7月30日 10:57:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/11714912.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定