Last active
August 29, 2015 14:22
-
-
Save jkramer/dc1aab946d9b9b73a092 to your computer and use it in GitHub Desktop.
URL Shortener with Mojolicious & Redis
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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