Logging Request Bodies For Golang REST APIs

Go does not support JSON natively, so our first step should be to learn how to decode the JSON format.
Thankfully Go comes with the “json” package which makes decoding easy and convenient to do.

A Basic Example

This simplified example comes from the Go docs

After handing our JSON stream over to a Reader, we’re using the `json.NewDecoder()` and `dec.Decode(&m)` to “translate” and read our data into the previously defined `Message` format.

The Request Body

When handling an HTTP request, we are doing something very similar already which helps us skip a step here.
I’ll also show you a nifty tool, we’ll be using for our logging output!

This is a very easy example but should give you a good idea of how to implement logging for your endpoints.

I’ve seen a few examples that go an extra step and read the body into an input buffer, to then cast it to a string. That is not necessary.

If you know of an easier way to achieve this or have any other feedback please let me know. I’ll update this article and am always eager to learn!