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.
Receiving binary data via HTTP in Go
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? –
Autocorrelation
How best to implement and parse it in Go, though any opinions on RESTful best practices would be appreciated as well. –
Cabalist
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)
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. –
Whitneywhitson
Limiting it would be wise, but I was mostly interested in an example to educate myself. –
Cabalist
© 2022 - 2024 — McMap. All rights reserved.