简体   繁体   English

在 golang 中解析 javascript Blob

[英]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.在 Go 中,您可以使用r.ParseMultipartForm()读取使用 Ajax 和FormData发送的Form ,该Form使用表单请求数据填充Form映射。

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.但是,我还没有找到解析 Blob 的方法。 The above code returns an empty map whenever instead of sending a form, I send a Blob.每当我发送一个 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.上面的 Go 代码不起作用。 Now, when I send this:现在,当我发送这个:

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

I can read form data without problems.我可以毫无问题地读取表单数据。

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.此外,请考虑提高 500 字节内存限制,因为较大的 blob 将写入临时文件。

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.我认为 javascript 将 blob 视为文件,因此您可以在r.MultipartForm.File查看它,获取文件头,打开它,读取、解码和解析。 Try for example尝试例如

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

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.我认为 Javascript 的 Blob 是一个十六进制字符串,最终可以转换为[]byte ,这是 Go 中 JSON 的标准类型。

// 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.您可能想要查看encoding/hexencoding/binary包,以解码从 Javascript 获取的 blob,以便在 Go 中键入[]byte ,如果还没有的话。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM