Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to Handle JSON data and Path Variable in Golang

How To Handle JSON Data And Path Variable In Golang

This quick golang tutorial help to understand of Path Variable,post payloads and send Json data to client using rest service.We will use "encoding/json" package for marshalling and un-marshalling data in golang. We will create simple example to understand how to access path variable into handler, posted json data and send json data to requester.

We will use go 1.9.2 to for demonstrate below functionality:

  • How to access Path varaible in golang.
  • How to access Post Json paylod in golang.
  • Convert HTTP responce 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:

vars := mux.Vars(r)
fmt.Println("The id is: ", vars["id"])

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.

func AddUser(w http.ResponseWriter, r *http.Request) {
type New_User struct {
	Name string `json:"name"`
	Job  string `json:"job"`
}

var user New_User
decoder := json.NewDecoder(r.Body)
decoder.Decode(&user)
fmt.Printf("%+v\n", user)
}

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.

func AddUser(w http.ResponseWriter, r *http.Request) {
type New_User_Resp struct {
	Name      string    `json:"name"`
	Job       string    `json:"job"`
	ID        string    `json:"id"`
	CreatedAt time.Time `json:"createdAt"`
}
defer resp.Body.Close()
fmt.Println("Test 123")
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
var data New_User_Resp
if err := json.NewDecoder(resp.Body).Decode(&data); err != nil {
	fmt.Println(err)
}

res, err := json.Marshal(&data)
w.Write(res)
}

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

The post How to Handle JSON data and Path Variable in Golang appeared first on Rest Api Example.



This post first appeared on Rest Api Example, please read the originial post: here

Share the post

How to Handle JSON data and Path Variable in Golang

×

Subscribe to Rest Api Example

Get updates delivered right to your inbox!

Thank you for your subscription

×