XML-RPC CGI server with Perl


Usually the standard path is /RPC2 for xml-rpc. So make this cgi work as /RPC2
Add the following line to your httpd.conf file and restart the server.

ScriptAlias /RPC2 /var/www/cgi-bin/xmlrpc.cgi

There are many advantages of running RPC server in CGI mode :
  • If the webserver is running in SSL (https) mode, then the client can do xml-rpc over https, and hence all the data is encrypted from client to server.
  • Apache environment variables are accessible for this script.
  • This can be integrated to read input from web forms and send data to diff machine to process

    
    #!/usr/bin/perl -w
    
    # This is a template to run a cgi script in apache, to read XML-RPC request on port :80
    # kalyan@rtns.org
    
    use Frontier::RPC2;
    my $rpc = new Frontier::RPC2;
    
    my $inputBuffer = "";
    
    my $methods = {
            'example.getSum' => \&getSum,
            'example.getDiff' => \&getDiff,
            'example.getProd' => \&getProd,
        'example.getMethods' => \&get_method_list
    };
    
    sub get_method_list {
            my @methods = keys %{$methods};
            return \@methods;
    }
    
    sub getSum {
        my $a = shift;
        my $b = shift;
        return $a+$b;
    }
    
    sub getDiff {
        my $a = shift;
        my $b = shift;
        return $a - $b;
    }
    
    sub getProd {
        my $a = shift;
        my $b = shift;
        return $a * $b;
    
    }
    
    # Prints the standard mime type for an XML-RPC responce
    print "Content-type: text/xml\n\n";
    
    # Reads the request in from STDIN up to CONTENT_LENGTH
    if (defined $ENV{"REQUEST_METHOD"} && $ENV{"REQUEST_METHOD"} eq 'POST') {
            if (exists($ENV{"CONTENT_TYPE"}) && $ENV{"CONTENT_TYPE"} eq 'text/xml' ) {
                    read(STDIN, $inputBuffer, $ENV{"CONTENT_LENGTH"});
            }
    }
    
    # Parses the request and formulates a responce. Then prints it to STDOUT
    my $responce = $rpc->serve($inputBuffer, $methods);
    
    print $responce . "\n";