Artemis | Blog | About & Contact

2018 / 01 / 29 (raw)

A very simple and fast URL shortener

Yesterday, I came home and, before going to sleep and half-asleep, I decided to code something.

What? I had no idea at the moment I did so.

So I wanted something dead-simple and minimalistic.

It serves only one purpose: shortening URLs.

For that reason, I have two routes: a POST route at which a user can create a new shortened URL, giving the target ; a GET route which, when passing the shortened code, will redirect the user to the target URL.

Database? Why bother?

We have a very simple identity: the file name is the shortened code, the file content is the target URL.

Which means that, when the user tries to retrieve a target (and be redirected), since they give us the shortened code, we can simply check for file existence in the storage folder and either return a 301 response with the target URL (if it could be found) or a 404 not found (if we couldn't find any file with this code).

Said that, I want to be able to easily count requests and errors.

I used a simple logging format composed of two files, respectively request-date(Y-m-d).log for requests and error-date(Y-m-d).log for errors.

Every incoming request starts with <-- and every error is contained in one line.

That means that we can know the request count and the error count, by day, by simply doing a grep '<--' request-{date}.log | wc -l for requests and wc -l error-{date}.log for errors.

Finally, for the web UI, I decided to simply go with Skeleton, as there's practically nothing.

The shortening request is made in AJAX, giving a clean result but in case the user disables Js, the URL will still be shortened and the code returned, or the error shown, so we're also okay here!