Home >Backend Development >Golang >How to Construct a URL-Encoded POST Request in Go using `http.NewRequest(...)`?
When creating a POST request with a URL-encoded body, the payload should be provided on the body parameter of the http.NewRequest(...) method, rather than appended to the URL as shown in the original code.
package main import ( "fmt" "net/http" "net/url" "strconv" "strings" ) func main() { apiUrl := "https://api.com" resource := "/user/" data := url.Values{} data.Set("name", "foo") data.Add("surname", "bar") u, _ := url.ParseRequestURI(apiUrl) u.Path = resource urlStr := u.String() // "https://api.com/user/" client := &http.Client{} r, _ := http.NewRequest(http.MethodPost, urlStr, strings.NewReader(data.Encode())) // URL-encoded payload r.Header.Add("Authorization", "auth_token=\"XXXXXXX\"") r.Header.Add("Content-Type", "application/x-www-form-urlencoded") resp, _ := client.Do(r) fmt.Println(resp.Status) }
By passing the URL-encoded data as the body of the request, the API can correctly interpret the payload and respond accordingly.
The above is the detailed content of How to Construct a URL-Encoded POST Request in Go using `http.NewRequest(...)`?. For more information, please follow other related articles on the PHP Chinese website!