Skip to content

Instantly share code, notes, and snippets.

Created October 10, 2014 02:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save anonymous/a26f6d298a827ee7e64f to your computer and use it in GitHub Desktop.
Save anonymous/a26f6d298a827ee7e64f to your computer and use it in GitHub Desktop.
use Mojolicious::Lite;
use Mojo::Pg;
use 5.20.0;
use experimental 'signatures';
helper pg => sub { state $pg = Mojo::Pg->new('postgresql://postgres@/test') };
# Prepare a table during startup
app->pg->migrations->from_this_class->migrate;
get '/' => sub ($c) {
my $db = $c->pg->db;
my $ip = $c->tx->remote_address;
# Store information about current visitor blocking
$db->query('insert into visitors values (now(), ?)', $ip);
# Retrieve information about previous visitors non-blocking
$db->query('select * from visitors limit 50' => sub ($db, $err, $results) {
return $c->reply->exception($err) if $err;
$c->render(json => [$results->hashes->each]);
});
};
app->start;
__DATA__
@@ migrations
-- 1 up
create table if not exists visitors (at timestamp, ip varchar(255));
-- 1 down
drop table if exists visitors;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment