読者です 読者をやめる 読者になる 読者になる

HTTP::Tinyでプログレスバーを表示

perl

Furlの FAQのものと同じですが。

#!perl
use strict;
use warnings;

use HTTP::Tiny;
use Term::ProgressBar;
use File::Basename;

my $url = shift or die "Usage $0 url";

my $ua = HTTP::Tiny->new(
    agent => 'sample ua',
);

my $bar = Term::ProgressBar->new({
    count => 1024, ETA => 'linear',
});

$bar->minor(0);
$bar->max_update_rate(1);

my $did_set_target = 0;
my $received_size = 0;
my $next_update = 0;
my $content = '';
my $res = $ua->request('GET', $url, {
    data_callback => sub {
        my ($buf, $res) = @_;

        unless ($did_set_target) {
            if ( my $cl = $res->{headers}->{'content-length'}) {
                $bar->target($cl);
                $did_set_target++;
            } else {
                $bar->target( $received_size + 2 * length($buf));
            }
        }

        $received_size += length($buf);
        $content .= $buf;
        if ($received_size >= $next_update) {
            $next_update = $bar->update($received_size)
        }
    },
});

open my $fh, '>', basename($url) or die "Can't open file\n";
print $fh $content;
close $fh;