Reputation: 5792
I am using below code to for POST method:
postData := url.Values{}
postData.Set("login_id", "test1")
postData.Set("api_key", "test2")
req, err := http.NewRequest("POST","http://example.com", strings.NewReader(postData.Encode()))
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
logger.Info(string(body))
os.Exit(3)
Values are not being set. When I checked with this: logger.Info(req.PostFormValue("login_id"))
there is a blank value. How can I debug/solve this issue?
Upvotes: 0
Views: 1205
Reputation: 38233
You need to specify the request's Content-Type
with req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
.
postData := url.Values{}
postData.Set("login_id", "test1")
postData.Set("api_key", "test2")
req, err := http.NewRequest("POST", "http://localhost:8080/", strings.NewReader(postData.Encode()))
if err != nil {
panic(err)
}
req.Header.Set("content-type", "application/x-www-form-urlencoded")
fmt.Println(req.PostFormValue("login_id"))
https://play.golang.org/p/nVVe_p6P8ph
Upvotes: 3
Reputation: 42413
When I checked with this:
logger.Info(req.PostFormValue("login_id"))
there is a blank value.
Of course they are. But that does not mean these values are not sent.
PostFormValue
is used to access the form values on a server Request
and not on a client Request
as your's req
.
Upvotes: 1
Reputation: 1610
PostForm is below.
package main
import (
"io/ioutil"
"net/http"
"net/url"
)
func main() {
resp, err := http.PostForm(URL, url.Values{"login_id": {"test1"}, "api_key": {"test2"}})
if err != nil {
panic(err)
}
defer resp.Body.Close()
respBody, err := ioutil.ReadAll(resp.Body)
if err == nil {
str := string(respBody)
println(str)
}
}
Upvotes: 0