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.

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.

You can access the full source code from my github repo here.

Parsing request body as JSON in Golang

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

From the postman response above, you can see that the json fields are captalized as they are in the struct’s definition. This may not always be what you want, especially if your API is mostly going to be consumed with JavaScript clients. JSON is native to JavaScript so we mostly want our json responses to be readily usable in JS. The capitalized fields arent’ syntactically wrong in JS but conventionally this isn’t done.

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.

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.

Show your support

Clapping shows how much you appreciated Edward Pie’s story.