4
我試圖調試一個奇怪的警告,當正在解析Plack::Request時,它出現在服務器日誌中。在某些情況下,破壞的UserAgent會發送一個類似「6375,6375」的Content-Length頭,這顯然是錯誤的。如何使用Perl爲HTTP請求發送不正確的Content-Length標頭?
爲了解決這個問題,我需要能夠重現警告。我想在一個單元測試中包含這個,這樣我可以確保在警告消失後沒有迴歸。但是,我在使用Perl時遇到了麻煩。我知道這可以使用netcat
和socat
完成,但我不希望單元測試必須依賴其他二進制文件進行安裝。
這裏是我試過:
#!/usr/bin/env perl
use strict;
use warnings;
use JSON::XS qw(encode_json);
use WWW::Mechanize;
my $mech = WWW::Mechanize->new;
$mech->add_handler(
request_prepare => sub {
my ($req, $ua, $h) = @_;
$req->headers->header('Content-Length' => 9999);
return;
}
);
my $json = encode_json({ foo => 'bar' });
$mech->post(
'http://example.com'/url,
'Content-Length' => 999,
Content => $json
);
輸出是:
Content-Length header value was wrong, fixed at /opt/perl5.16.3/lib/site_perl/5.16.3/LWP/Protocol/http.pm line 260.
200
這完全是太有幫助了我。 :)
如果我使用HTTP::Request和LWP::UserAgent,它是相同的最終結果。
所以,我試了HTTP::Tiny。
#!/usr/bin/env perl
use strict;
use warnings;
use DDP;
use HTTP::Tiny;
use JSON::XS qw(encode_json);
my $http = HTTP::Tiny->new;
my $json = encode_json({ foo => 'bar' });
my $response = $http->request(
'POST',
'http://example.com'/url',
{ headers => { 'Content-Length' => 999, },
content => $json,
}
);
p $response;
輸出是:
{ content => "Content-Length missmatch (got: 13 expected: 999)
",
headers => {
content
-length => 49,
content-type => "text/plain",
},
reason => "Internal Exception",
status => 599,
success => "",
url => "http://example.com'/url",
}
同樣,也有幫助。在這一點上,我可以使用一些建議。