public
Last active

Grabbing website titles, non-blocking.

  • Download Gist
titles.pl
Perl
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
#!/usr/bin/env perl
 
use Mojolicious::Lite;
app->ua->max_redirects(10);
 
my @urls = qw/mojolicio.us mojocasts.com/;
 
helper 'render_dumper' => sub {
my $self = shift;
$self->render( text => $self->dumper( \@_ ) );
};
 
any '/one' => sub {
my $self = shift;
$self->render_later;
$self->ua->get($urls[0] => sub {
my ($ua, $tx) = @_;
$self->render_dumper($tx->res->dom->at('title')->text);
});
};
 
any '/two' => sub {
my $self = shift;
$self->render_later;
my @titles;
$self->ua->get($urls[0] => sub {
my ($ua, $tx) = @_;
push @titles, $tx->res->dom->at('title')->text;
$self->ua->get($urls[1] => sub {
my ($ua, $tx) = @_;
push @titles, $tx->res->dom->at('title')->text;
$self->render_dumper(@titles);
});
});
};
 
any '/all' => sub {
my $self = shift;
$self->render_later;
my $delay = Mojo::IOLoop->delay(sub{
my $delay = shift;
my @titles = map { $_->res->dom->at('title')->text } @_;
$self->render_dumper(@titles);
});
$self->ua->get( $_ => $delay->begin ) for @urls;
};
 
app->start;

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.