Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 68 lines (51 sloc) 1.256 kb
3fe11a8 @rcaputo Create a consumer that tracks the number of pending HTTP reqeusts.
authored
1 #!/usr/bin/env perl
2 # vim: ts=2 sw=2 noexpandtab
3
4 use warnings;
5 use strict;
6 use lib qw(../lib);
7
8 {
9 package ConcurrentHttpClient;
10 use Moose;
11 extends 'Reflex::Base';
12
13 use HttpClient;
14 use Reflex::Trait::Watched qw(watches);
15
16 watches http_client => (
17 is => 'ro',
18 isa => 'HttpClient',
19 default => sub { HttpClient->new() },
20 );
21
22 has pending => (
23 is => 'rw',
24 isa => 'Int',
25 default => 0,
26 );
27
28 sub requests {
29 my ($self, @http_requests) = @_;
30
31 foreach my $request (@http_requests) {
32 $self->http_client()->request( $request );
33 }
34
35 $self->pending( $self->pending() + @http_requests );
36 }
37
38 sub on_http_client_response {
39 my ($self, $response) = @_;
40 $self->re_emit( $response, -name => 'response' );
41
42 return if $self->pending( $self->pending() - 1 );
43
44 $self->emit( -name => "empty" );
45 };
46 }
47
48 ### Main usage.
49
50 use HTTP::Request;
51
52 my $client = ConcurrentHttpClient->new();
53 $client->requests(
54 map { HTTP::Request->new( GET => $_ ) }
55 'http://poe.perl.org',
56 'http://duckduckgo.com/',
57 'http://metacpan.org/',
58 'http://perl.org/',
59 'http://twitter.com/',
60 );
61
62 while (my $event = $client->next()) {
63 last if $event->_name() eq 'empty';
64 print $event->response()->code(), " = ", $event->request()->uri(), "\n";
65 }
66
67 exit;
Something went wrong with that request. Please try again.