How to Set Proper Content-Type for Multipart POST Requests in Go?

Mary-Kate Olsen
Release: 2024-10-24 03:30:31
Original
271 people have browsed it

How to Set Proper Content-Type for Multipart POST Requests in Go?

HTTP Multipart Requests in Go

Creating multipart requests, commonly used for sending data in specific formats, can be achieved using the multipart package in Go. Let's explore how to tackle this.

Consider the following scenario: sending a multipart POST request that consists of both JSON data and a boundary. This boundary separates different parts of the request.

Numerous attempts have been made, as illustrated in the given code snippet. However, the server consistently returns a 200 HTTP error, indicating that the message type is unsupported.

To resolve this, we need to correctly set the Content-Type of each part. Here's the modified code:

<code class="go">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(),
)</code>
Copy after login

By setting the Content-Type: application/json for the part containing the JSON data, we ensure that the server can correctly interpret the request. The boundary parameter is also set appropriately to match the expected format.

The above is the detailed content of How to Set Proper Content-Type for Multipart POST Requests in Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!