Home >Backend Development >Golang >How to Construct a URL-Encoded POST Request in Go using `http.NewRequest(...)`?

How to Construct a URL-Encoded POST Request in Go using `http.NewRequest(...)`?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-30 14:40:15767browse

How to Construct a URL-Encoded POST Request in Go using `http.NewRequest(...)`?

URL-Encoded POST Request with 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!

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