Checkout https://www.gophersumit.com/series/web-server/ for more.
working with JSON data
Sending and accepting JSON data is very common while building REST Services. Let's see how we can build web server in Go to work with JSON data.
To work wit JSON data we will be using
encoding/json standard library package. We have two main constructs while working with JSON data.
Encoding is the process of serializing data. In Go, for working with JSON, struct data is serialized in byte slice.
For serialization, we use
json.Marshal() method. Let's see Marshalling in action.
First we define our struct type that will be Marshalled:
We then initialize this using struct literal:
And for serialization we use
Marshal which returns byte slice and error.
Decoding/Unmarshaling is opposite of what we did above. This is used to extract value from byte slice back to struct,
To Unmarshal byte slice , we use
Complete code for Marshalling and Unmarshaling :
encoding/json package only accesses the exported fields of struct types. That is the reason we have capitalized all struct fields. If we want to serialize only few fields of struct, we should leave rest of fields as un-exported. If we Marshal and Unmarshal same code using below defined struct,
pincode will not be serialized.
Customizing encoding of struct using tags
The encoding of each struct field can be customized by the format string stored under the “json” key in the struct field's tag.
We can use add tags to struct field extension to easily add and customize how struct will be Marshalled.
omitempty signals to leave out struct fields which are empty.
If we now Marshal this struct value, it will generate below JSON.
Notice how casing is small and for Pincode, we have used
pin in JSON.
Return json from web server
Let's build a simple web server to return json data. We will use the same struct that we have defined above.
To send JSON data, first step is to set content type to application/json so that browser will treat it as JSON data. We do this by using
Set method on Header of response writer.
To send struct as JSON data, we need to create a
NewEncoder first. NewEncoder is used to write to
This encoder has
Encode method which writes to writer interface. For web apps, we write to ResponseWriter interface.
Complete web server is as simple as :
Accepting JSON data
Most of the web-apis will require to accept json data.
Let's see how we can accept JSON data.
To accept JSON data, we first create an instance of Decoder.
decoder := json.NewDecoder(r.Body)
We then extract JSON data in struct by using
Complete web app code :