Home > Article > Backend Development > Send POST request with form data using http.PostForm function
Use the http.PostForm function to send a POST request with form data
In the http package of the Go language, you can use the http.PostForm function to send a POST request with form data. The prototype of the http.PostForm function is as follows:
func PostForm(url string, data url.Values) (resp *http.Response, err error)
where url represents the URL address of the POST request , data is a parameter of type url.Values, used to store form data.
The following is a sample code that uses the http.PostForm function to send a POST request with form data:
package main import ( "fmt" "net/http" "net/url" ) func main() { // 构造表单数据 formData := url.Values{} formData.Set("username", "admin") formData.Set("password", "123456") // 发送POST请求 resp, err := http.PostForm("https://www.example.com/login", formData) if err != nil { fmt.Println("发送请求出错:", err) return } defer resp.Body.Close() // 解析响应内容 if resp.StatusCode == http.StatusOK { fmt.Println("登录成功!") } else { fmt.Println("登录失败!") } }
In the sample code, we first construct a formData object of type url.Values , used to store form data. Then, we call the http.PostForm function to send a POST request, passing in the URL address and form data as parameters. Finally, we determine whether the login is successful by parsing the returned http.Response object.
It should be noted that the http.PostForm function will automatically set the Content-Type to application/x-www-form-urlencoded, and encode the form data and send it to the server as the request body.
In actual applications, we can further expand the code according to needs, such as adding more form fields, processing returned response results, etc.
Summary: It is very convenient to use the http.PostForm function to send POST requests with form data. You can easily send data to the server and obtain the response results. By rationally utilizing this function, we can implement more interesting functions.
The above is the detailed content of Send POST request with form data using http.PostForm function. For more information, please follow other related articles on the PHP Chinese website!