Binary file uploads

If you need to do a binary file upload, e.g. via;

  1. curl -X POST -F "attachment=@/tmp/somefile.txt" http://localhost:9090/v1/files

then your request will contain the binary data directly and there is no way to model this using gRPC.

What you can do instead is to add a custom route directly on the mux instance.

Custom route on a mux instance

Here we’ll setup a handler (handleBinaryFileUpload) for POST requests:

  1. // Create a mux instance
  2. mux := runtime.NewServeMux()
  3. // Attachment upload from http/s handled manually
  4. mux.HandlePath("POST", "/v1/files", handleBinaryFileUpload)

And then in your handler you can do something like:

  1. func handleBinaryFileUpload(w http.ResponseWriter, r *http.Request, params map[string]string) {
  2. err := r.ParseForm()
  3. if err != nil {
  4. http.Error(w, fmt.Sprintf("failed to parse form: %s", err.Error()), http.StatusBadRequest)
  5. return
  6. }
  7. f, header, err := r.FormFile("attachment")
  8. if err != nil {
  9. http.Error(w, fmt.Sprintf("failed to get file 'attachment': %s", err.Error()), http.StatusBadRequest)
  10. return
  11. }
  12. defer f.Close()
  13. //
  14. // Now do something with the io.Reader in `f`, i.e. read it into a buffer or stream it to a gRPC client side stream.
  15. // Also `header` will contain the filename, size etc of the original file.
  16. //
  17. }