2012-07-30 02:57 阅读 132


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条回答 默认 最新

  • 已采纳
    dqcj32855 dqcj32855 2012-07-30 06:59

    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 := os.TempFile("", "my_app_prefix")
    if err!=nil {log.Fatal("cannot open temp file", err)}
    defer f.Close()
    io.Copy(f, req.Body)
    点赞 评论 复制链接分享