Jenia Be Nice Please
Jenia Be Nice Please

Reputation: 2693

How to use multipart in golang

I need to generate a multipart post request of this form:

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

(if you know how to generate the above with Curl, please give me a tip too ;)) I tried the following:


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

   ...

}

But the server cannot read the content of body. It responds with a 200 HTTP request but it says that the message type is not supported.

So how do I generate a multipart/mixed request that is of the form above?

Thanks kindly in advance for your help.

Upvotes: 4

Views: 5521

Answers (1)

Thundercat
Thundercat

Reputation: 120941

Use it like this:

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.

Upvotes: 7

Related Questions