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
Linda HamiltonOriginal
2024-12-28 15:06:10992browse

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())

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

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

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")

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

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

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!

Statement:
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