Home > Backend Development > Golang > I can't add header to specific multipart in golang

I can't add header to specific multipart in golang

PHPz
Release: 2024-02-10 18:18:18
forward
727 people have browsed it

我无法将标头添加到 golang 中的特定多部分

In this article, php editor Xinyi will introduce you to the solution on how to add specific multi-part headers in golang. Headers are key components in HTTP requests and responses, used to convey various metadata information. However, sometimes we may encounter an issue that specific multipart headers cannot be added to the request in golang. In what follows, we’ll provide a simple and effective solution to help you overcome this problem. let's start!

Question content

The api I use requires the content-type of the multipart form to be content-type: audio/wav but if you add a file part, _ := writer.createformfile("audio_file", "test2.wav") It makes the content type application/octet-stream

I have tried before: part.header.set("content-type", "audio/wav") But the header is not defined.

This is the curl request data minus the valid binary:

content-disposition: form-data; name="audio_file"; filename="test2.wav"
content-type: audio/wav
Copy after login

Here is my request minus the rejected binary data:

Content-Disposition: form-data; name="audio_file"; filename="test2.wav"
Content-Type: application/octet-stream
Copy after login

Solution

Call createpart directly instead of the createformfile convenience method. Set the content type in the header used to create the widget.

h := make(textproto.MIMEHeader)
h.Set("Content-Disposition",
    fmt.Sprintf(`form-data; name="%s"; filename="%s"`, "audio_file", "test2.wav"))
h.Set("Content-Type", "audio/wav")
part, err := writer.CreatePart(h)
Copy after login

The above is the detailed content of I can't add header to specific multipart in golang. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template