6

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.

cmhobbs
  • 2,469
  • 3
  • 24
  • 30
  • How do you mean with "go about receiving", are you referring to how to best implement it and parse it in GO, or are you referring to how to best send it in a RESTful manner? – Cleric Jul 30 '12 at 03:05
  • How best to implement and parse it in Go, though any opinions on RESTful best practices would be appreciated as well. – cmhobbs Jul 30 '12 at 03:09

1 Answers1

20

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)
Grokify
  • 15,092
  • 6
  • 60
  • 81
Elazar Leibovich
  • 32,750
  • 33
  • 122
  • 169
  • 2
    Note that this particular way of handling reads the whole request body into memory. In the real world, you probably want to limit the size, store the data on disk, or something else. – Evan Shaw Jul 30 '12 at 08:36
  • Limiting it would be wise, but I was mostly interested in an example to educate myself. – cmhobbs Jul 31 '12 at 20:24