make a http request with a custom body as form url encoded in go

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.go
import (
    "net/http"
    "net/url"
    "strings"
)

func main() {
    // Create form data
    values := url.Values{}
    values.Set("key1", "value1")
    values.Set("key2", "value2")
    formBody := strings.NewReader(values.Encode())

    // Create HTTP request
    req, err := http.NewRequest("POST", "http://example.com/foo", formBody)
    if err != nil {
        // Handle error
    }
    req.Header.Set("Content-Type", "application/x-www-form-urlencoded")

    // Send HTTP request
    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        // Handle error
    }
    defer resp.Body.Close()

    // Process HTTP response
    // ...
}
671 chars
32 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