Clone request headers in Villa Perl CGI for LWP UserAgent

I have a perl CGI application that I want to take the headers of user requests and include them in the request request of LWP :: UserAgent. Basically, the goal is to replicate the incoming user headers and use them for a separate request.

I tried to create the headers myself, but when I try to display the CGI headers and then my cloned UserAgent headers, they are not exactly the same. Here is what I got:

my $ cgi = new CGI;
my% headers = map {$ _ => $ cgi-> http ($ _)} $ cgi-> http;
my $ req_headers = HTTP :: Headers-> new (% headers);
my $ ua = LWP :: UserAgent-> new (default_headers => $ req_headers);
print Dumper $ ua-> default_headers;

Basically,% of headers and $ ua-> default_headers are not identical. $ ua-> default_headers has an agent that identifies itself as a perl script. I can manually set $ ua-> agent (""), but there are other drawbacks, and the headers are still not identical.

What is the best way to do what I want? There should be a simpler solution ...

+3
source share
1 answer

It seems that the problem is with the name of the incoming HTTP headers compared to what HTTP :: Headers uses.

HTTP_, HTTP:: Headers ( ). , : ( ), HTTP:: Headers '-' '_' .

map , :

# remove leading HTTP_ from keys, note: this assumes all keys have pattern
# HTTP_*
%headers = map { ( /^HTTP_(.*?)$/ ) => $cgi->http($_) } $cgi->http;

script, :

my $cgi = CGI->new;
my %headers = map { $_ => $cgi->http($_) } $cgi->http;
my $req_headers = HTTP::Headers->new( %headers );
my $ua = LWP::UserAgent->new( default_headers => $req_headers );

print "Content-type: text/plain\n\n";
print Dumper($ua->default_headers);
print Dumper( \%headers );

# remove HTTP_ from $_
%headers = map { ( /^HTTP_(.*?)$/ ) => $cgi->http($_) } $cgi->http;
$req_headers = HTTP::Headers->new( %headers );
$ua = LWP::UserAgent->new( default_headers => $req_headers );

print "headers part deux:\n";
print Dumper( $ua );

,

+3

Source: https://habr.com/ru/post/1750781/


All Articles