Home > Backend Development > Golang > How to Make URL-Encoded POST Requests with Go's `http.NewRequest(...)`?

How to Make URL-Encoded POST Requests with Go's `http.NewRequest(...)`?

Linda Hamilton
Release: 2024-12-28 15:06:10
Original
1042 people have browsed it

How to Make URL-Encoded POST Requests with Go's `http.NewRequest(...)`?

HTTP URL-Encoded POST Requests via http.NewRequest(...)

Form-encoded data is a fundamental technique for sending data over HTTP. This data encoding format is widely supported and used in various scenarios. Let's explore an approach to make POST requests using http.NewRequest(...) while maintaining control over request headers.

To transmit URL-encoded data, the payload should not be appended to the URL but rather passed via the request body. This involves creating a bytes.Buffer that holds our form-encoded data:

data := url.Values{}
data.Set("name", "foo")
data.Set("surname", "bar")
encoder := bytes.Buffer{}
encoder.WriteString(data.Encode())
Copy after login

Now, we can create our http.Request and attach the buffer to the body:

request, err := http.NewRequest(http.MethodPost, urlStr, &encoder)
Copy after login

Since we're dealing with form-encoded data, we need to set the proper content type in the headers:

request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
Copy after login

Finally, we're ready to send off the request:

resp, err := http.DefaultClient.Do(request)
Copy after login

By following these steps, you can successfully make URL-encoded POST requests with http.NewRequest(...) and custom request headers. Remember that the URL-encoded data should be sent in the request body, and the content type header should be set accordingly.

The above is the detailed content of How to Make URL-Encoded POST Requests with Go's `http.NewRequest(...)`?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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