Reputation: 2499
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.
Upvotes: 6
Views: 7999
Reputation: 33593
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)
Upvotes: 20