Pocket URL is a tiny URL shorting service, I built PocketURL after watching an excellent talk from GopherCon 2017 Advanced Testing with Go by Mitchell Hashimoto from HashiCorp. Testing in Go wasn’t a new concept to me I was really inspired by how he explained the methods they used to test at HashiCorp, and helped re-enforce the concept of how writing good tests and testable code.
I was so excited by what I had learned I really wanted to make sure it stuck and the best way to do that is to build, as I result pocket-URL was born. I had a clear goal of building a simple well tested API and I think I accomplished just that.
First I outlined exactly my requirements for the project;
- Redirect users to a URL based on a short URL that has been created.
- Adding of new URLs
- Removing of URLs
Based on my requirements, it was clear I needed 3 endpoints to manage this and the powerful standard library of Go would have every feature I needed so no need to use anything 3rd party.
Next I began mapping out what my tests were going to look like. I decided on only making 1 test function with sub tests, this was because I would need to test in a set order add, redirect and remove. Then all I needed to do was build a table of every possible URL combo errors and valid, this helped me ensure complete test converge of my HTTP handlers.
Now my tests were built it was simply a case of building out the core application, building my tests first really helped to keep my code clean. I decided on simply storing the data only in memory, this was a simple application that didn’t require and persistence. I chose to store the data in a string indexed map, I did this, so I could easily lookup generated short URLs without having to do any sort of loop.
Since my tests had already defined what my HandleFuncs needed to do, it was very simple to build my functionality and ensure all was working as expected. I did run into a bug that caused a knock-on effect but because of my tests I was able to quickly spot the problem just by seeing what sub-test was failing.
This project really helped reinforce the need for test driven development on projects of all sizes. At a later date I should consider adding support for SQL to PocketURL as persistence is quite important in a URL shortening service, however since this was just an experiment project it wasn’t a core requirement to help keep things simple.Project Link