Receiving binary data via HTTP in Go
Asked Answered
C

1

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.

Cabalist answered 30/7, 2012 at 2:57 Comment(2)
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
C
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)
Cinema answered 30/7, 2012 at 6:59 Comment(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.Whitneywhitson
Limiting it would be wise, but I was mostly interested in an example to educate myself.Cabalist

© 2022 - 2024 — McMap. All rights reserved.