HTTP Logging and Go API Template Updates

Dan Gillis
Oct 13, 2018 · 3 min read

I built my first Go library! httplog provides middleware which logs http requests and responses along with a few other features I find useful. I thought it might be helpful for some. At the very least, I tried to document the library reasonably well, spending a lot of time developing the README and ensuring the GoDoc was in good shape. I learned a lot through this exercise.

I also restructured my Go API template repository to try and shape it based on Mat Ryer’s fantastic “How I write Go HTTP services after seven years” post. I think/hope that I got the fundamentals right from the lessons he was trying to impart and have baked them into this template repo.

At a high level, using the template and httplog library, you can send a request that looks like this:

and get a response body that looks like this:

Note the audit object, which is provided by httplog

If turned on, the request and/or response are logged either to stdout or a PostgreSQL database (or both) and can then be used for investigative purposes, etc. You can also set options whether or not to log request/response headers and body. For instance, this example service takes password in the body, you should not log this and would turn off request body logging for this API.

As I mentioned above, I found the post from Mat Ryer to be extremely compelling and completely restructured my template. I now have a server struct, a la

I have a routes.go file where all my routing lives…

and my handlers hang off the server with request and response structs defined within the handler…

I haven’t incorporated everything (still need to get to the testing stuff, etc.), but it’s a good start.

There’s a lot more happening in the Go API template (password hashing, graceful error handling, etc.) and I plan to bake even more into it as I continue to learn. For instance, this week’s release of Go Cloud’s Wire makes me want to revisit my template again and add in dependency injection. I just added it to my list, actually….

Finally, I’ve been coding Go in a vacuum for a year as I don’t actually know anyone else who writes Go. I know it’s cliche, but I really do welcome feedback to help me learn. Thanks!

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade