Last active
May 3, 2018 12:58
-
-
Save kraih/5855296 to your computer and use it in GitHub Desktop.
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 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