在 Golang 中如何使用多部分(multipart)?

3
我需要生成一个这样的多部分POST请求:
POST /blabla HTTP/1.1
Host: 2.2.2.2
Authorization: moreblabla Content-Type: multipart/mixed; boundary=--rs0q5Jq0M2Yt08jU534d1q Content-Length: 347
Node: 1.1.1.1.1
--rs0q5Jq0M2Yt08jU534d1q Content-Type: application/json

{"hello" : "world"}
--rs0q5Jq0M2Yt08jU534d1q

如果您知道如何使用Curl生成上述内容,请也给我一些提示;)

我尝试了以下方法:


var jsonStr = []byte(`{"hello" : "world"}`)

func main() {

    body := &bytes.Buffer{}
    writer := multipart.NewWriter(body)

    part, _:= writer.CreateFormField("")

    part.Write(jsonStr)
    writer.Close()

    req, _ := http.NewRequest("POST", "blabla", body)
    req.Header.Set("Content-Type", writer.FormDataContentType())

   ...

}

但是服务器无法读取请求体内容。它会响应一个200 HTTP请求,但表示消息类型不受支持。

那么我该如何生成一个类似上述形式的multipart/mixed请求呢?

非常感谢您的帮助。


你想生成multipart/mixed,但调用writer.FormDataContentType()会创建一个multipart/form-data:使用writer.Boundary自己组装Content-Type头。你的部分不是表单字段,因此不能使用方便的函数writer.CreateFormFields,但应该使用writer.CreatePart,它允许你将适当的Content-Type设置为application/json。 - Volker
1个回答

5

使用方法如下:

body := &bytes.Buffer{}
writer := multipart.NewWriter(body)

part, _ := writer.CreatePart(textproto.MIMEHeader{"Content-Type": {"application/json"}})
part.Write(jsonStr)

writer.Close()

req, _ := http.NewRequest("POST", "http://1.1.1.1/blabla", body)
req.Header.Set("Content-Type", "multipart/mixed; boundary="+writer.Boundary())

在沙盒中运行它


你在这里设置边界和路径在哪里?此外,FormDataContentType 不正确吗? - The Fool
是的,抱歉,您关于边界的观点是正确的,我们甚至不能使用multipart/mixed路径。当我评论https://developers.google.com/gmail/api/guides/batch时,我没有正确阅读这里的实现。 OP问题中的内容类型仍然是multipart/mixed。我手动创建了具有该内容类型的标头。 - The Fool
1
类似这样的内容 w.Header().Set("Content-Type", "multipart/mixed; boundary="+writer.Boundary()) - The Fool

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接