Go - HTTP POST request FORM data



In this source code example, we will show how to send an HTTP Post request with form data in Golang.

All Golang source code examples at https://www.sourcecodeexamples.net/p/golang-source-code-examples.html

Go - HTTP POST request FORM data

The 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

The data is sent in the body of the request; the keys and values are encoded in key-value tuples separated by '&', with a '=' between the key and the value.

We send a POST request to the https://httpbin.org/post page.

Let's create a file named "go_example.go" and add the following source code to it:


package main

import (
    "encoding/json"
    "fmt"
    "log"
    "net/http"
    "net/url"
)

func main() {

    data := url.Values{
        "name":       {"Admin"},
        "occupation": {"Engineer"},
    }

    resp, err := http.PostForm("https://httpbin.org/post", data)

    if err != nil {
        log.Fatal(err)
    }

    var res map[string]interface{}

    json.NewDecoder(resp.Body).Decode(&res)

    fmt.Println(res["form"])
}

Run the following command to execute the go_example.go file:

G:\GoLang\examples>go run go_example.go
map[name:Admin occupation:Engineer]

Related Golang Source Code Examples

Comments