Submit POST request in Golang with header
I create my form as follows:
form := url.Values{} form.Add("region", "San Francisco") if len(params) > 0 { for i := 0; i < len(params); i += 2 { form.Add(params[i], params[i+1]) } testLog.Infof("form %v", form) Now if i use
resp, err = http.PostForm(address+r.Path, form) then everything works fine, I get a response with the expected cookie.
However, I would like to add a header, in this case I cannot use PostForm , so I created my POST request manually, for example:
req, err := http.NewRequest("POST", address+r.Path, strings.NewReader(form.Encode())) Then I add material to the header and submit the request
req.Header.Add("region", "San Francisco") resp, err = http.DefaultClient.Do(req) But the form has not been received, and my response does not contain a cookie.
When I type req , it looks like this: nil :
&{POST http://localhost:8081/login HTTP/1.1 1 1 map[Region:[San Francisco]] {0xc420553600} 78 [] false localhost:8081 map[] map[] <nil> map[] <nil> <nil> <nil> <nil>} You need to add a content type to your request.
You said that http.PostForm worked to look at the source :
func PostForm(url string, data url.Values) (resp *Response, err error) { return DefaultClient.PostForm(url, data) } OK, so this is just a wrapper around the PostForm method on the client by default. See which :
func (c *Client) PostForm(url string, data url.Values) (resp *Response, err error) { return c.Post(url, "application/x-www-form-urlencoded", strings.NewReader(data.Encode())) } OK, calling the Post method and passing in "application/x-www-form-urlencoded" for bodyType and doing the same for the body you are doing. Let's look at the Post method
func (c *Client) Post(url string, bodyType string, body io.Reader) (resp *Response, err error) { req, err := NewRequest("POST", url, body) if err != nil { return nil, err } req.Header.Set("Content-Type", bodyType) return c.doFollowingRedirects(req, shouldRedirectPost) } So the solution to your problem is to add
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")