Go Web Application JSON response


API response

For API, json data is very simple to handle. Receive parameters and return as json, client side (web and mobile) can handle easily.

To get JSON response, we need to understand JSON handle in go.

In previous blog, I explained about JSON handle in go and simple way to handle json data in web.

These are entries.

JSON in go

To support JSON data, use “encoding/json” package.

This package has json Marshal, Unmarshal method

  • Marshal : struct(data) -> json object
  • UnMarshal : byte data -> struct (data)

In UnMarshal, to use string to byte, we can get struct data from string.

Return data of Marshal can use response data.



package web

import (

// json response
type DataJson struct {
	Name  string
	Title []string

func jsonRes(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	data := &DataJson{
		Name:  "Hoo Foo",
		Title: []string{"1st", "3rd", "1st"},
	json, _ := json.Marshal(data)

The step

  1. Set header content-type application/json
  2. Create data (struct)
  3. Call Marshal for response
  4. Write data
Professional Programmer2