Skip to content

Instantly share code, notes, and snippets.

@diegok
Created October 25, 2011 15:28
Show Gist options
  • Save diegok/1313138 to your computer and use it in GitHub Desktop.
Save diegok/1313138 to your computer and use it in GitHub Desktop.
Mojo::UserAgent with gzip and timing support
=attr ua
User agent configured with logger and timing.
=cut
has ua => sub {
my $self = shift;
my $log = $self->log;
$log->debug( "Building user agent" );
my $ua = Mojo::UserAgent->new;
$ua->max_redirects(3);
$ua->log($log);
$ua->ioloop->connect_timeout(5);
$ua->on( start => sub {
my ( $ua, $tx ) = @_;
my @time = gettimeofday();
$tx->req->headers->header('Accept-Encoding' => 'gzip');
$tx->on( finish => sub {
my $tx = shift;
$log->info( sprintf("[%s] %s (%.2f)",
$tx->res->code || 'ERR',
$tx->req->url,
$self->timer( tv_interval(\@time) )
) );
if ($tx->res->headers->header('Content-Encoding')) {
$tx->res->body(Compress::Zlib::memGunzip($tx->res->body))
if $tx->res->headers->header('Content-Encoding') =~ /gzip/;
}
});
});
return $ua;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment