Parsing JSON Request Body & Return JSON Response With Golang
This post is in response to a question someone asked on my earlier post which addressed crafting middlewares in Golang. Naturally, it’s a good question to ask since most modern APIs consume and produce JSON data format predominantly.
And, if you love my posts on Golang, then do well to subscribe to my Go Rapidly course on Youtube to get notified of the latest videos I post every other day.
Golang has encoding/json package which is used for marshalling (converting objects into json) and unmarshalling (converting json into objects). In RESTFul APIs, you can read raw request bodies by accessing the Body field on a net/http.Request object. You can also write json to response output stream by passing the slice of byte that defines your json to the Write function of net/http.ResponseWriter object.
In the snippet below, I’ve implemented an endpoint which echoes request body back to the response stream after setting it’s time field to the server’s current local time.
Below is also a postman demonstration of how to pass json request body to the API endpoint defined above .
Note that the password field has been removed from the response json even though it was part of the request body. This is because passwords are sensitive data and shouldn’t be returned as part of API responses. This is achieved by adding the json:”-” tag to any field in your struct that you’d like to not include in the marshalling process.
Generally, json.Marshal returns byte and error so you’ll have to check if error isn’t nil before proceeding to use the byte returned.
Controlling How Fields Are Marshalled Into Json
To control the marshalling and unmarshalling processes, you can uses tags in the struct’s definition to affect how the fields in the structs are serialized to json. For example, I can add json:”username” tag to the Username field in the User struct so that my json response will have username instead of the capitalized Username.
You can also use json:”omitempty” to ignore empty fields in the marshalling process.
Finally, if you love my posts on Golang, then do well to subscribe to my Go Rapidly course on Youtube to get notified of the latest videos I post every other day.
Thanks for your time. Leave your comments, suggestions, questions, and criticisms below and don’t forget to follow me for more such byte-sized lessons.