Mojo :: UserAgent get()与用户定义的回调 [英] Mojo::UserAgent get() with userdefined callback

查看:176
本文介绍了Mojo :: UserAgent get()与用户定义的回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用 Mojo :: UserAgent 编写类似的内容,可以设置等效选项(Range:content_file:content_cbsize_hint).

Is there a way to write something like this with Mojo::UserAgent ,having the possibility to set equivalent options ( Range, :content_file, :content_cb, size_hint).

#!/usr/bin/env perl
use warnings;
use 5.12.0;
use LWP::UserAgent;
use File::Basename;

my $url = 'ftp://ftp.vim.org/pub/vim/runtime/spell/en.utf-8.spl';
my $file = basename $url;
my $ua = LWP::UserAgent->new();
my $bytes = 0;

open my $fh, '>>:raw', $file or die $!;
my $res = $ua->get( 
    $url,
    'Range' => "bytes=$bytes-",
    ':content_cb' => sub { 
        my ( $chunk, $res, $proto ) = @_;
        print $fh $chunk; 
        state $old_size = 0;
        my $size = tell $fh;
        my $total;
        say 'chunk size :', $size - $old_size;
        if ( $total = $res->header( 'Content-Length' ) ) {
            say 'total size : ', $total;
            say 'downloaded : ', $size;
            say 'remaining  : ', $total - $size;
        }
        say "";
        $old_size = $size;
    }
);
close $fh;

say $res->status_line;

推荐答案

#!/usr/bin/env perl

use 5.12.0;
use warnings;

use File::Basename qw(basename);
use Mojo::UserAgent ();

my $url = 'ftp://ftp.vim.org/pub/vim/runtime/spell/en.utf-8.spl';
my $ua  = Mojo::UserAgent->new();
my $tx  = $ua->build_tx(GET => $url);

open(my $fh, '>:raw', basename($url)) or die($!);
$tx->req->headers->header(range => 'bytes=0-');
$tx->res->content->on(read => sub {
    print($fh $_[1]);
    say('chunk size: ', length($_[1]));
    say('total size: ', $_[0]->headers->content_length);
    say('downloaded: ', $_[0]->body_size);
    say('');
});
$ua->start($tx);
close($fh);

say($tx->res->code, ' ', $tx->res->message);

这篇关于Mojo :: UserAgent get()与用户定义的回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆