How to Parse JSON data and Path Variable in Golang

This quick golang tutorial help to understand of path variable and parse json data.We will learn: How to use post payloads, How to send and receive json data into client using rest service.We will parse json data into golang. We will use "encoding/json" package for marshaling and UN-marshaling data in golang.

Lets create simple example in golang to access path variable into handler. We also post json data and send json data to requester.

We will use go 1.9.2 to for demonstrate below functionality:

  • How to access Path variable in golang.
  • How to access Post JSON payload in golang.
  • Convert HTTP response into Json and send to requester.
  • How to access path Variable in Go

    The variable is very useful to send limited number of variable using URI to server, like 'api/v1/test/id/1', where id is the path variable and value is 1, You can define path variable without key name as well, like 'api/v1/test/1'. You can access path variable into handler method using MUX package as like below:

    How to access POST JSON Payload in Go

    POST HTTP method helpful to send large scale of data to server, When you need to send large amount of data that GET will not handle, You can send data using POST type request. We will use "encoding/json" package to handle json data into go server side.

    We have created struct for user data, Then we have created empty user variable of New_User type.Encoded HTTP request body and stored into 'decoder' variable and after that decoded json data.We have print struct mapped data into console using fmt.Printf method.

    How to Convert Response Body Into JSON

    We have consume thirst party rest api and got HTTP response from third rest api, We need to decode json data and send json as a response, we will convert response body data into json data and send to client.

    We have used NewDecoder method, that returns a new decoder that reads from resp.Body and mapped with New_User_Resp struct.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.