我应该如何使用Mojo :: UserAgent处理HTML META标签?

bri*_*foy 5 perl mojolicious mojo-useragent

我必须使用一些配置错误的Web服务器,所以我开始处理HTML元标记以将信息反馈回Web用户代理对象。我在Mojolicious中尝试了多种方法来完成此操作,并决定在响应中查找“完成”事件。我的目标是使其余代码几乎不可见,因此过程甚至都不知道这种情况在发生。

但是,由于我不能完全放下手指,这只是不适合我。除了中的特定代码外process_meta_options,还有其他Mojolicious方式可以做到这一点吗?例如,具有用户定义的回调的Mojo :: UserAgent get()使用该read事件,但我倾向于认为这可能会干扰事情。或者,我可能只是想得太多。

use v5.20;

use feature qw(signatures);
no warnings qw(experimental::signatures);

use Data::Dumper;
use Mojo::UserAgent;

my $ua = Mojo::UserAgent->new;

my $tx = $ua->build_tx( GET => 'http://blogs.perl.org' ); 

$tx->res->on(
    finish => \&process_meta_options
    );

$tx = $ua->start( $tx );
say "At end, charset is ", $tx->res->content->charset;

sub process_meta_options ( $res ) {
    $res
        ->dom
        ->find( 'head meta[charset]' )  # HTML 5
        ->map( sub {
            my $content_type = $res->headers->header( 'Content-type' );
            return unless my $meta_charset = $_->{charset};
            $content_type =~ s/;.*//;
            $res->headers->header( 'Content-type', "$content_type; charset=$_->{charset}" );
            } );
    }
Run Code Online (Sandbox Code Playgroud)

bri*_*foy 1

我认为答案正是我想到的。我还没有找到我更喜欢的东西。

use v5.20;

use feature qw(signatures);
no warnings qw(experimental::signatures);

use Data::Dumper;
use Mojo::UserAgent;

my $ua = Mojo::UserAgent->new;

my $tx = $ua->build_tx( GET => 'http://blogs.perl.org' ); 

$tx->res->on(
    finish => \&process_meta_options
    );

$tx = $ua->start( $tx );
say "At end, charset is ", $tx->res->content->charset;

sub process_meta_options ( $res ) {
    $res
        ->dom
        ->find( 'head meta[charset]' )  # HTML 5
        ->map( sub {
            my $content_type = $res->headers->header( 'Content-type' );
            return unless my $meta_charset = $_->{charset};
            $content_type =~ s/;.*//;
            $res->headers->header( 'Content-type', "$content_type; charset=$_->{charset}" );
            } );
    }
Run Code Online (Sandbox Code Playgroud)