I was playing around with some url shorteners like http://bitly.com and thought it would be a cool idea to make such a service myself. Now while diving more into the topic I came up with the following three approaches of implementing an url shortener. Of course there are more approaches I will only mention those three since they are good enough for a small service of personal use.
- Generate a string of random characters. The easiest method is to generate a string of random characters like upper and lower case characters and numbers. Every time an url is entered you can check your database if the real link already exists and in that case just return the shortened url. If it doesn’t exist just generate a new one. Generating strings of fixed length is a good idea.
- Taking the original url and run some fancy encryption and compression algorithms. After that shorten the result to the desired length and you are done.
- Generate a GUID. This is easy if you use C# and SQL Server since you can generate the GUID both on SQL Server or use a C# class for this. Compress the generated GUID and format it to your needs.
I started to implement the first idea with generating random strings, since this is the most easy one I think and is totally sufficient for my needs.
The only thing you have to take care of is the database I think. While this will work well on a small basis, maybe the queries will kill down performance if you reach some popularity with your service. Something I will never find out