REST API Tutorial

How to Consume POST Http Request in Goland In JSON

Summary of learning

We will create HTTP Post type request using ECHO framework, restful request will consume third party POST API using golang http module. Http module help to create request to access GET/POST/DELETE type method request.We will create json data to send post data to rest api and get response as a json data.

We will create HTTP Post type request using ECHO framework, restful request will consume third party POST API using golang http module. Http module help to create request to access GET/POST/DELETE type method request.We will create json data to send post data to rest api and get response as a json data.

We will import following packages into server.go file,

import (
	"github.com/labstack/echo"
	"github.com/labstack/echo/middleware"
	"net/http"
	"fmt"
	"test-api/controllers"
)

We will run below command to get all packages,
go get

We will create group of api and rest end points into main method of server.go file,

v1 := e.Group("/api/v1")
v1.POST("/addUser", controllers.AddUser)

We will create model interface into models/types.go file,

package models

type User struct {
   Fname   string `json:"first_name"`
   Lname string `json:"last_name"`
}
type Resp struct {
    Code                    int      `json:"code"`
    Message                 string      `json:"message"`
}

We have mapped posted json first_name key with Fname and last_name to Lname.

We will create User.go file into project/controllers folder and create method to call third party api using HTTP post.

package services
import (
   "net/http"
   "fmt"
   "test-api/models"
   "encoding/json"
   "bytes"
)
func AddUser() models.Resp {
   res := new(models.User)
   var jsonData = []byte(`{"first_name":"`+res.Fname+`", "last_name":"`+res.Lname+`"}`)
   client := &http.Client{}
   req, err := http.NewRequest("POST", "http://localhost/add_user/", bytes.NewBuffer(jsonData))
   req.Header.Set("Content-Type", "application/json")
   resp, er := client.Do(req)
   fmt.Println(resp.Body)

   if er != nil{
      log.info("Error in reqeust send")
   }

   if err != nil{
      log.info("Error in reqeust create")
   }
   defer resp.Body.Close()
   
   fmt.Println(resp.StatusCode)
   if resp.StatusCode == 200{
      log.Info("Successfully! Added User")
 
   }
   var data models.Resp
   if err := json.NewDecoder(resp.Body).Decode(&data); err != nil {
      fmt.Println(err)
   }
   
   return data
}

Imported http packages to send request, models to access struct interface, json package to encode/decode json data into go application and bytes package use to implements functions for the manipulation of byte slices.

Created AddUser() method and return json response as models.Resp type, we have mapped posted json data to models.User struct, then converted into bytes to send data into POST Body.We have created HTTP POst request using golang http package NewRequest method that have three parameters: HTTP method type, url and body data parameters.

I have set Content-Type into request header using req.Header.Set() method, finally send request using client.Do(req) method, that have request instance as parameter, We are storing success data into resp and error into er variable.

If the request has been successfully completed, then we will get HTTP 200 status code and response mapped to data variable and return to requester, Now open command line and reach your project folder, run below command,
test-api$ go run server.go

You will get message server is running if every thing is fine and access api/v1/addUser using rest client like Postman etc.

I hope its help you.

If you have requirements that needs our attentioN

Please feel free to contact us

We would love to hear from you

Share with your network

Facebook
Twitter
LinkedIn
WhatsApp
Email

This tutorial is intended to cover all the essentials steps and insights to understand How to Consume POST Http Request in Goland In JSON

Genislab Technologies

Learn further