Skip to content

Instantly share code, notes, and snippets.

@kraih
Last active May 3, 2018 12:58
Show Gist options
  • Save kraih/5855296 to your computer and use it in GitHub Desktop.
Save kraih/5855296 to your computer and use it in GitHub Desktop.
#!/usr/bin/env perl
use Mojolicious::Lite;
use Coro;
use Mojo::IOLoop;
# Magical class for calling a method non-blocking (with a closure) and
# rescheduling the current coroutine until it is done
package with::coro {
use Coro;
sub AUTOLOAD {
my ($method) = our $AUTOLOAD =~ /^with::coro::(.+)$/;
my ($done, @args);
shift->$method(@_ => sub { shift, @args = @_; $done++ });
cede until $done;
return wantarray ? @args : $args[0];
}
};
# Reschedule main coroutine
Mojo::IOLoop->recurring(0 => sub {cede});
# Wrap dispatcher in coroutine
hook around_dispatch => sub {
my $next = shift;
async { $next->() };
};
# Looks blocking but the request is non-blocking
get '/' => sub {
my $self = shift;
my $tx = $self->ua->with::coro::get('mojolicio.us');
$self->render(text => $tx->res->dom->at('title')->text);
};
app->start;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment