Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send a POST request in Go?

Tags:

go

I am trying to make a POST request but I can't get it done. Nothing is received on the other side.

Is this how it is supposed to work? I'm aware of the PostForm function but I think I can't use it because it can't be tested with httputil, right?

hc := http.Client{} req, err := http.NewRequest("POST", APIURL, nil)  form := url.Values{} form.Add("ln", c.ln) form.Add("ip", c.ip) form.Add("ua", c.ua) req.PostForm = form req.Header.Add("Content-Type", "application/x-www-form-urlencoded")  glog.Info("form was %v", form) resp, err := hc.Do(req) 
like image 429
hey Avatar asked Jun 30 '14 15:06

hey


People also ask

How do I make a post request on go?

learn-go (5 Part Series)Create a new folder called http-request . Open the main.go and import the necessary packages. Create a struct that models the data received from the API. Create a POST request using the method http.

What is go HTTP client?

Go is a language designed by Google for use in a modern internet environment. It comes with a highly capable standard library and a built-in HTTP client.

What is net http in Golang?

The net/http interface encapsulates the request-response pattern in one method: type Handler interface { ServeHTTP(ResponseWriter, *Request) } Implementors of this interface are expected to inspect and process data coming from the http. Request object and write out a response to the http. ResponseWriter object.


2 Answers

You have mostly the right idea, it's just the sending of the form that is wrong. The form belongs in the body of the request.

req, err := http.NewRequest("POST", url, strings.NewReader(form.Encode())) 
like image 138
Innominate Avatar answered Oct 19 '22 01:10

Innominate


I know this is old but this answer came up in search results. For the next guy - the proposed and accepted answer works, however the code initially submitted in the question is lower-level than it needs to be. Nobody got time for that.

//one-line post request/response... response, err := http.PostForm(APIURL, url.Values{     "ln": {c.ln},     "ip": {c.ip},     "ua": {c.ua}})  //okay, moving on... if err != nil {   //handle postform error }  defer response.Body.Close() body, err := ioutil.ReadAll(response.Body)  if err != nil {   //handle read response error }  fmt.Printf("%s\n", string(body)) 

https://golang.org/pkg/net/http/#pkg-overview

like image 23
dlxsrc Avatar answered Oct 19 '22 01:10

dlxsrc