在golang中解析javascript Blob

Parse javascript Blob in golang

本文关键字:javascript Blob golang      更新时间:2023-09-26

在Go中,你可以读取使用Ajax发送的表单,并使用r.ParseMultipartForm()读取FormData发送的表单,这会用表单请求数据填充Form映射。

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

但是,我还没有找到解析 Blob 的方法。每当我发送 Blob 而不是发送表单时,上面的代码都会返回一个空映射。也就是说,当我发送这个时:

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

上面的 Go 代码不起作用。现在,当我发送这个:

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

我可以毫无问题地读取表单数据。

r.ParseMultipartForm(500)

也许这里返回了一个错误?尝试捕获错误:

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

此外,请考虑提高 500 字节的内存限制,因为较大的 blob 将写入临时文件。

我认为javascript将blob视为文件,因此您可以在r.MultipartForm.File中查找它,获取文件头,打开它,读取,解码和解析。尝试例如

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

我认为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]}

你可能想要查看encoding/hexencoding/binary包,以解码从 Javascript 获取的 blob 以在 Go 中键入 []byte(如果还没有)。