Learn How to make JSON POST request in GoLang
In this article, you will learn about how to make JSON POST requests in the Go Language.
JSON refers to the JavaScript Object Notation which is widely used in web development to transmit data. It is lightweight and human-readable. In the Go language, you can make a JSON POST request but to do so you need to import some packages that are available in GO. First of all, let’s see an example of how JSON formatted data looks like in the below:
{
"StudentName": "Deven Rathore",
"StudentId" : "170203065",
"StudentGroup": "Computer Science"
}
Here, JSON data are wrapped in between double quotes and for writing multiple lines you need to give a comma. This formatted data is understandable and can be read easily.
In the Go language, you will get support for HTTP client and server with the help of the “net/http” package, and working with JSON you need to import t”json” package. Both are available in the Go language. If you want to work with JSON in the Go language, you will need to import these packages. See the below code example to get things more clear:
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
type StudentDetails struct {
StudentName string `json:"StudentName"`
StudentId string `json:"StudentId"`
StudentGroup string `json:"StudentGroup"`
}
func main() {
studentDetails := StudentDetails{
StudentName: "Deven Rathore",
StudentId: "170203065",
StudentGroup: "Computer Science",
}
body, _ := json.Marshal(studentDetails)
resp, err := http.Post("<https://reqres.in/api/users>", "application/json", bytes.NewBuffer(body))
if err != nil {
panic(err)
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusCreated {
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
panic(err)
}
jsonStr := string(body)
fmt.Println("Response: ", jsonStr)
} else {
fmt.Println("Get failed with error: ", resp.Status)
}
}
/*
Output:
Response: {
"StudentName":"Deven Rathore",
"StudentId":"170203065",
"StudentGroup":"Computer Science",
"id":"868",
"createdAt":"2021-12-11T12:35:03.092Z"
}
*/
This is how you can make JSON POST request in the Go language.