Multipart Requests in Go
Creating multipart requests in Go can be challenging, especially when adhering to specific request formats. To understand how to effectively use multipart requests, let's consider an example where the target request takes the 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
Previously, an attempt was made to generate such a request using multipart.NewWriter and a default part creation, which led to issues with content recognition. To address this, the following approach can be utilized:
body := &bytes.Buffer{} writer := multipart.NewWriter(body) // Create the part with the appropriate mime type part, _ := writer.CreatePart(textproto.MIMEHeader{"Content-Type": {"application/json"}}) part.Write(jsonStr) writer.Close() req, _ := http.NewRequest("POST", "blabla", body) req.Header.Set("Content-Type", "multipart/mixed; boundary="+writer.Boundary())
By specifying the content type while creating the part, the request can adhere to the expected format and successfully transmit the required data.
The above is the detailed content of How to Construct Multipart Requests with Mime Types in Go. For more information, please follow other related articles on the PHP Chinese website!