How to send a POST request in Go?

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

Similar Posts

  • |

    git push error

    $ git push error: The requested URL returned error: 403 Forbidden while accessing https://github.com/HarryWei/hummer.git/info/refs fatal: HTTP request failed Replace (or add) url=ssh://git@github.com/HarryWei/hummer.git with url=https://git@github.com/HarryWei/hummer.git under “[remote “origin”]” section in ~/.gitconfig file. Reference:http://stackoverflow.com/questions/7438313/pushing-to-git-returning-error-code-403-fatal-http-request-failed Read more: Git push error under CENTOS 6.7 Push and Pull data from Restful Service in Asp.net MVC Application using Angular JS Fixing…

  • Pass-less ssh auto-login problem

    I configured the Linux password-less automatic ssh login as in this post . However, it still does not work for me. Any method to check it? The log in log /var/log/secure may give some clue on it. For example: Aug 20 23:16:10 doppler sshd[11143]: Authentication refused: bad ownership or modes for directory /home/useraaa tells us that…

  • How to make a swap partition

    How to make a swap partition on Linux? First, make a new partition (or reuse an existing one if you like). I suggest using cfdisk to create it: https://www.systutorials.com/docs/linux/man/8-cfdisk/ Then, turn the new partition (say, /dev/sdc1) to a swap # mkswap /dev/sdc1 Lastly, turn it on # swapon /dev/sdc1 You can check whether its status…