Go - HTTP POST request JSON data

This source code example shows how to send a POST request with data in JSON format in Golang.

We generate a POST request to the httpbin.org/post webpage. The post data is taken from a map and transformed into a string with encoding/json package.

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

Go - HTTP POST request JSON data

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


package main

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

func main() {

    values := map[string]string{"name": "Admin", "occupation": "Engineer"}
    json_data, err := json.Marshal(values)

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

    resp, err := http.Post("https://httpbin.org/post", "application/json",
        bytes.NewBuffer(json_data))

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

    var res map[string]interface{}

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

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

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