Probably most of the people are already familiar with existing URL Shortener Websites, like Ow.ly, Tinyurl, Bitly and Goo.gl.
They provide short url generation, which is the main purpose of their existence, but also some other features like analytics, custom domains, etc.
In my case, I didn’t need many of the extra features (at least for now) and wanted something simple, just a short url generator based on a long path/url, with my custom domain on it also.
So I ended up building a custom solution for Grails, that is simple and does what I needed at that moment.
Creating Grails short url domain
Basically I created a new domain entity that will hold the association between the original url path with the new generated token.
The seed attribute will store the string used to generate the url token, so if pathAsSeed is true the path will be used as the seed,
otherwise a random uuid string is utilized, and the murmur3_32 hashing function is responsible to create it based on seed variable.
Creating Grails short url service
The main idea of the algorithm is to be able to generate a token based on the incoming url path. As you probably know hashing algorithms have certain probability to collide, so to make
it more robust I added a collision resolver up to 3 tries, in this case, but you can tweak it as your desire.
So anytime that createShorUrl method is executed it will return the same exact token for the incoming path.
Creating Grails short url controller
A new controller was added to handle short url translation into a normal path. Another option could be to use a Grails Filter.
Adding Grails short url to UrlMappings file
Added a new path to UrlMappings.groovy file.
Execution example
The following code snippet is an example of shortUrlService.createShortUrl method execution.