Reputation: 3
I have a page setup on my webserver with an 'email address' box and a submit button. I have it so when it is submitted, it sends a post request to check if it exists in my database. I have been using Go to try and send this POST request. However, I need to send the request body as the following:
demo_mail=<email>
I haven't found anything remotely useful online, only posts asking how to send the data with JSON rather than a string. I currently have the following code which runs but fails to send the POST request with the post data above.
req, err := http.NewRequest("POST", "<MY PAGE>", ioutil.NopCloser(bytes.NewBufferString("demo_mail=" + email)))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8")
req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.80 Safari/537.36")
resp, err := client.Do(req)
if err != nil {
color.Red("Error.")
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
if strings.Contains(string(body), "Success") {
fmt.Println("Email exists")
} else {
fmt.Println("Fail")
}
Any help is appreciated.
Upvotes: 0
Views: 1554
Reputation: 123320
The body you expect is actually correctly sent but maybe not in the way you want:
POST /foo HTTP/1.1
...
Transfer-Encoding: chunked
...
Content-Type: application/x-www-form-urlencoded
...
17
demo_mail=<[email protected]>
0
Since you've wrapped your string into a io.NopCloser
it will assume that the length is not known up-front. It will therefore use chunked transfer encoding to send each chunk returned from the io.Reader
prefixed by its length and once everything done the final chunk with length 0.
If you don't want to have this behavior you need to provide a buffer where the length is known up-front. This can be done by simply removing the ioutil.NopCloser
around the bytes.NewBufferString
:
req, err := http.NewRequest("POST", "<MY PAGE>", bytes.NewBufferString("demo_mail=" + email))
With this the request will use Content-length
instead of chunked transfer encoding and the body will only contain the string:
POST /foo HTTP/1.1
...
Content-Length: 23
...
Content-Type: application/x-www-form-urlencoded
...
demo_mail=<[email protected]>
Upvotes: 2