I recently combined all my various blogs into this one and then realised that, yet again, the length of my name is a pain. Especially when it comes to URLs. I also realised that I’d never tried to build a URL shortener, so I did. Full source available here.
There are a few tutorials around about writing one in PHP, but I decided to use Go. The basic idea is the same.
The URL shortener uses a single table with the following structure:
I think the fields are self-explanatory.
The code itself is really simple. The idea is to handle every HTTP request and capture the path of the URI. Look the path up in the database, and return either a redirect or not found. I decided to use go-sql-driver for the mysql integration and gorilla mux for more advanced request routing.
As you can see, all we do in main is open the connection to the database given the passed-in connection parameters, then set up a simple request routing table.
The single handler is almost as straightforward. It queries the database to see if the short URL is registered and then either returns a redirect or not found, or fatals in the case of a SQL error. An extra feature that I might use later in a dashboard view is that it tracks the access count and last accessed time for each registered short URL.
We also don’t need to worry about little Bobby Tables as Go escapes the parameters for us.
One final wrinkle is that I use Dreamhost for hosting and so can’t run a native Go server. However, with a little mod_rewrite trickery I can persuade Apache to forward requests to my server. Here’s the relevant lines of the .htaccess file:
This ensures that the given port isn’t already the one our server is listening on, and then redirects to the host with the write port number.
Currently, short URLs have to be added manually through a SQL interface. Ideally, there’d be some UI for adding short URLs, and maybe even generating them through some hash function. Though checking for and handling hash collisions in a database is a pain.