"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Create Multipart HTTP Requests with Gomultipart in Golang?

How to Create Multipart HTTP Requests with Gomultipart in Golang?

Published on 2024-11-16
Browse:642

How to Create Multipart HTTP Requests with Gomultipart in Golang?

How to Use multipart in Go

multipart in Golang is a powerful tool for creating multipart HTTP requests. This can be particularly useful when sending data that includes both text and file content.

Solution

To create a multipart form request, follow these steps:

  1. Instantiate a bytes.Buffer and a multipart.Writer object.
  2. Use the multipart.Writer to create multipart.Part objects, one for each part of the request.
  3. Set the Content-Type header of the request to the value returned by writer.FormDataContentType().
  4. Write the contents of the request parts to the multipart.Writer.
  5. Call writer.Close() to complete the request.

Example

In your example, you would create a multipart mixed request as follows:

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

part, err := writer.CreatePart(textproto.MIMEHeader{"Content-Type": {"application/json"}})
if err != nil {
    // handle error
}

part.Write(jsonStr)

writer.Close()

req, err := http.NewRequest("POST", "blabla", body)
if err != nil {
    // handle error
}

req.Header.Set("Content-Type", "multipart/mixed; boundary=" writer.Boundary())

Bonus Tip: Using cURL

You can also generate a multipart request using cURL with the following command:

curl -F "field=value" -H "Content-Type: multipart/mixed; boundary=boundary" http://1.1.1.1/blabla
Release Statement This article is reprinted at: 1729690430 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3