views:

274

answers:

2

Unfortunately, I'm not familiar with Perl, so asking here. Actually I'm using FCGI with Perl.

I need to 1. accept a POST request -> 2. send it via POST to another url -> 3. get results -> 4. return results to the first POST request (4 steps).

To accept a POST request (step 1) I use the following code (found it somewhere in the Internet):

$ENV{'REQUEST_METHOD'} =~ tr/a-z/A-Z/;
if ($ENV{'REQUEST_METHOD'} eq "POST") {
    read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
}
else {
    print ("some error");
}

@pairs = split(/&/, $buffer);
foreach $pair (@pairs) {
    ($name, $value) = split(/=/, $pair);
    $value =~ tr/+/ /;
    $value =~ s/%(..)/pack("C", hex($1))/eg;
    $FORM{$name} = $value;  
}

The content of $name (it's a string) is the result of the first step. Now I need to send $name via POST request to some_url (step 2) which returns me another result (step 3), which I have to return as a result to the very first POST request (step 4).

Any help with this would be greatly appreciated.

Thank you.

+3  A: 

To accept the POST, you can use the hand-rolled code you've shown, but the very best way is to make use of CGI (which is now a core module so it should be in your Perl distribution). For passing on a POST to somewhere else, you can use LWP::UserAgent

#/usr/bin/perl
use strict;
use warnings;
use CGI;
use LWP::UserAgent;

my $cgi = CGI->new;   # Will process post upon instantiation
my %params = $cgi->Vars;
my $ua = LWP::UserAgent->new;
my $postTo = 'http://www.somewhere.com/path/to/script';
my $response = $ua->post($postTo, %params);

if ($response->is_success) {
    print $response->decoded_content;  # or maybe $response->content in your case
} else {
 die $response->status_line;
}




}
Tony Miller
+2  A: 

I highly recommend that you do not try to solve this problem yourself but instead use existing libraries to make you life MUCH easier. The best part of Perl is the vast collection of existing libraries. See http://search.cpan.org/

Good starting places include CGI.pm or a web framework like Catalyst.

The code you've quoted is very buggy. Coincidentally, there was just a post by a popular Perl blogger dissecting this exact code.

Chris Dolan