To make an HTTP request with a custom body as URL-encoded form data in Go, you can use the net/http
package provided by Go's standard library. Here's an example code snippet that demonstrates how to create and send a POST request with URL-encoded form data as the body:
main.go671 chars32 lines
In this code snippet:
url.Values
is used to create form data with key-value pairs.strings.NewReader()
is used to create a reader for the form data.http.NewRequest()
is used to create an HTTP request with the form data reader as the body.req.Header.Set()
is used to set the Content-Type header to application/x-www-form-urlencoded
.client.Do()
is used to send the HTTP request and get the response.defer resp.Body.Close()
is used to close the response body to avoid resource leaks.Note that error handling is omitted in this code snippet for brevity. In production code, you should always check errors and handle them properly.
gistlibby LogSnag