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:

request

and get a response body that looks like this:

request

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:

request

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

request

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

request

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!