【问题标题】:How to use multipart in golang如何在golang中使用multipart
【发布时间】:2022-01-20 22:12:35
【问题描述】:

我需要生成这种形式的多部分发布请求:

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 但调用 writer.FormDataContentType() 来创建 multipart/form-data:使用 writer.Boundary 自己组装 Content-Type 标头。您的部分不是表单字段,因此您不能使用便利功能 writer.CreateFormFields 但您应该使用 writer.CreatePart 它可以让您将适当的 Content-Type 设置为 application/json。

标签: http go curl


【解决方案1】:

像这样使用它:

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())

Run it on the playground.

【讨论】:

  • 这里的边界和路径在哪里设置?还有,FormDataContentType 是不是不对?
  • 是的,抱歉,关于边界,您是对的,我们甚至不能使用多部分/混合的路径。当我评论 developers.google.com/gmail/api/guides/batch 时,我没有正确阅读这里的实现。 OPs 问题中的内容类型仍然是多部分/混合的。我使用该内容类型手动创建了标题。
  • 对,或者类似w.Header().Set("Content-Type", "multipart/mixed; boundary="+writer.Boundary())
猜你喜欢
  • 2016-11-29
  • 2018-06-16
  • 1970-01-01
  • 2017-06-12
  • 1970-01-01
  • 2018-09-12
  • 1970-01-01
  • 2017-01-05
相关资源
最近更新 更多