Home > Backend Development > Golang > How to Make a URL-Encoded POST Request Using Go's `http.NewRequest(...)`?

How to Make a URL-Encoded POST Request Using Go's `http.NewRequest(...)`?

Barbara Streisand
Release: 2024-12-19 11:31:10
Original
605 people have browsed it

How to Make a URL-Encoded POST Request Using Go's `http.NewRequest(...)`?

Make a URL-Encoded POST Request Using http.NewRequest(...)

Building upon the fundamental principles of HTTP requests, developers often require the ability to construct requests with specific characteristics, such as those with a URL-encoded POST payload. This article will delve into the specifics of crafting such requests using the versatile http.NewRequest(...) method.

Traditionally, URL-encoded data is included within the URL query string. However, utilizing the http.NewRequest(...) method allows for greater control over header management. In this scenario, leaving the request body empty while appending the query to the URL is not a suitable approach.

The solution lies in providing the URL-encoded payload as a string via the io.Reader interface, which is elegantly demonstrated in the following 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.Set("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) // Output: 200 OK
}
Copy after login

By incorporating the URL-encoded string within the request body via strings.NewReader(), the HTTP request is properly configured to deliver the intended payload. This revised approach eliminates the 400 BAD REQUEST error and ensures that the API correctly interprets the transmitted data.

The above is the detailed content of How to Make a URL-Encoded POST Request Using Go's `http.NewRequest(...)`?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template