Post request from server to site

54 views
Skip to first unread message

ape...@gmail.com

unread,
Jul 26, 2016, 7:23:56 AM7/26/16
to golang-nuts
hi i need to connect via post request to site . What package more usefull for this ? I m use iris framework for build my service. Iris use fasthttp lib. Maybe fasthttp helps me ?

Im create a function where i m send params. On output i need a body of page

func goToSite(param string) {
#pseudo code
params
go to with post url(params)
return fetch page

How i can do this ?
Please advice :)

Konstantin Khomoutov

unread,
Jul 26, 2016, 7:55:48 AM7/26/16
to ape...@gmail.com, golang-nuts
Use the standard net/http package and the function Post() it exports.
You'll need to provide the type of the payload of your request to that
function, and something implementing the io.Reader interface which
represents the payload itself (the body of your request).
The function returns a pointer to the value of type net/http.Response,
which contains a field named Body which implements the io.ReadCloser
interface. So you're supposed to read the data from that Body value
and then call its Close() method.

So basically you do

import (
"bytes"
"io"
"net/http"
"strings"
)

const req = `{"foo": "bar"}`

resp, err := http.Post("http://site/resource",
"text/json; charset=utf-8",
strings.NewReader(s))
if err != nil {
// Deal with the error
}
defer resp.Body.Close()

// Now check the resp.StatusCode to see
// the outcome of the response.
// Further processing logic might/should heavily
// depend on this.

var data bytes.Buffer
_, err = io.Copy(&data, resp.Body)
if err != nil {
// Deal with the error
}

return data.Bytes()

Note that there is really way more to think of; some notes in no
particular order:

* POST request suppose you actually _post_ some data to the requested
resource. This data must be formatted using the format the
resource understands, and you must properly indicate it.

In my example it's a nonsense JSON-formatted data in the
form of a constant string.

* You usually want to indicate to the resource what type of data
you expect and are able to handle by using the properly formatted
HTTP header "Accept".

* When the remote answered with a response, you have to do several
checks on it:

- See its status code to make a decision of whether the operation was
successful of not.
- If you decide to actually process the body of the server's response,
check the response's Content-Type to see if the response is in the
format you know how to handle (and its encoding ("charset" in HTTP
parlance), too).

* No matter whether you decide to process the response body or not,
you have to read it and close; otherwise the net/http code won't be
able to reuse this connection.
Reply all
Reply to author
Forward
0 new messages