Federico
Federico

Reputation: 3920

Parse javascript Blob in golang

In Go, you can read a form sent using Ajax and FormData using r.ParseMultipartForm(), which populates the Form map with form request data.

func form(w http.ResponseWriter, r *http.Request) {
    r.ParseMultipartForm(500) //
    fmt.Fprintf(w, "This is the value of %+v", r.Form)
}

However, I haven't found a method to parse Blobs. The above code returns an empty map whenever instead of sending a form, I send a Blob. That is, when I send this:

var blob = new Blob([JSON.stringify(someJavascriptObj)]);
//XHR initialization, etc. etc.
xhr.send(blob);

the Go code above doesn't work. Now, when I send this:

var form = new FormData(document.querySelector("form"));
//...
xhr.send(form);

I can read form data without problems.

Upvotes: 3

Views: 4108

Answers (3)

Uvelichitel
Uvelichitel

Reputation: 8490

I think javascript treats blob as file, so your can look it in r.MultipartForm.File, get file header, open it, read, decode and parse. Try for example

r.ParseMultipartForm(500) 
fmt.Fprintf(w, "This is the value of %+v", *r.MultipartForm.File)
}

Upvotes: 1

Pandemonium
Pandemonium

Reputation: 8390

I presume Javascript's Blob is a hex string which can eventually be converted to []byte, which is a standard type for JSON in Go.

// Once you get the blob
blobString := `7b22666f6f223a205b22626172222c202262617a222c2039395d7d`

b, _ := hex.DecodeString(blobString)
json := string(b)
fmt.Println(json) // prints out {"foo": ["bar", "baz", 99]}

You might want to look into encoding/hex and encoding/binary packages to decode your blob acquired from Javascript to type []byte in Go, if it's not already.

Upvotes: 0

Mark
Mark

Reputation: 7071

r.ParseMultipartForm(500)

Perhaps an error is being returned here? Try capturing the error:

if err := r.ParseMultipartForm(500); err != nil {
    http.Error(w, err.Error(), http.StatusInternalServerError)
}

Also, consider raising the 500 byte memory limit as larger blobs will be written to temporary files.

Upvotes: 1

Related Questions