How to send a POST request in Go?

Posted on

How to send a POST request in Go? For example, send a POST of content like ‘id=8’ to a URL like https://example.com/api.

In Go, the http package provides many common functions for GET/POST. Related to POST requests, the package provides 2 APIs:

Post

Post issues a POST to the specified URL.

func (c *Client) Post(url, contentType string, body io.Reader) (resp *Response, err error)

PostForm

PostForm issues a POST to the specified URL, with data’s keys and values URL-encoded as the request body. The Content-Type header is set to application/x-www-form-urlencoded.

func (c *Client) PostForm(url string, data url.Values) (resp *Response, err error)

Examples

Use PostForm to submit forms

import (
    "net/http"
    "net/url"
)

// ...

response, err := http.PostForm("https://example.com/api", url.Values{"id": {"8"}})

if err != nil {
    // postForm error happens
} else {
    defer response.Body.Close()
    body, err := ioutil.ReadAll(response.Body)

    if err != nil {
        // read response error
    } else {
        // now handle the response
    }
}

Use Post

Here, we post a JSON to an API endpoint as an example

values := map[string]string{"id": "8"}
jsonValue, _ := json.Marshal(values)
resp, err := http.Post("https://example.com/api", "application/json", bytes.NewBuffer(jsonValue))
// check err
// read from resp, remember do close the body

Related Posts