在Golang中,我們可以使用以下方法來處理表單請求:
http.Post
或http.PostForm
方法來發送POST請求,并將表單數據作為參數傳遞。這些方法會自動設置Content-Type為application/x-www-form-urlencoded
。resp, err := http.PostForm("http://example.com/form", url.Values{
"name": {"John Doe"},
"email": {"john@example.com"},
})
url.Values
來構建查詢字符串,并將其附加到URL中。values := url.Values{
"name": {"John Doe"},
"email": {"john@example.com"},
}
url := "http://example.com/form?" + values.Encode()
resp, err := http.Get(url)
http.NewRequest
方法創建一個PUT請求,并將表單數據作為請求體發送。values := url.Values{
"name": {"John Doe"},
"email": {"john@example.com"},
}
req, err := http.NewRequest("PUT", "http://example.com/form", strings.NewReader(values.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
client := &http.Client{}
resp, err := client.Do(req)
http.NewRequest
方法創建一個DELETE請求,并將表單數據作為請求體發送。values := url.Values{
"name": {"John Doe"},
"email": {"john@example.com"},
}
req, err := http.NewRequest("DELETE", "http://example.com/form", strings.NewReader(values.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
client := &http.Client{}
resp, err := client.Do(req)
以上是一些常用的處理表單請求的方法,可以根據具體需求選擇適合的方法來發送表單數據。