Skip to content

Instantly share code, notes, and snippets.

@jkramer
Last active August 29, 2015 14:22
Show Gist options
  • Save jkramer/dc1aab946d9b9b73a092 to your computer and use it in GitHub Desktop.
Save jkramer/dc1aab946d9b9b73a092 to your computer and use it in GitHub Desktop.
URL Shortener with Mojolicious & Redis
#!/usr/bin/env perl
use strict;
use warnings;
use Mojolicious::Lite;
use Mojo::Redis2;
use Mojo::URL;
use Mojo::Util qw( b64_encode );
plugin 'config';
helper redis => sub { state $r = Mojo::Redis2->new };
post '/' => sub {
my ($c) = @_;
my $url = Mojo::URL->new($c->param('url') // '');
if($url->is_abs) {
my $id = $c->redis->hget('url.original', $url);
if(!$id) {
$id = b64_encode $c->redis->incr('url.count');
$id =~ s/=*\s*$//;
$c->redis->hset("url.shortened", $id, $url);
$c->redis->hset("url.original", $url, $id);
}
$c->render(text => $c->config->{host} . '/' . $id);
}
else {
$c->render(text => 'Invalid URL', status => 400);
}
};
get '/:id' => sub {
my ($c) = @_;
my $url = $c->redis->hget('url.shortened', $c->param('id'));
$url ? $c->redirect_to($url) : $c->render(status => 404, text => 'No such URL');
};
app->start;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment