[Purdue-pm] Simple Web Service
Dave Jacoby
jacoby at purdue.edu
Wed Jan 19 07:05:49 PST 2011
Yesterday, I said that someone should be able to make a simple web
service that could handle addition in ten minutes. I didn't time how
long it took me to code this but it is 40 lines long and about 10 or 15
are lines I use most everywhere in CGI programs.
As written, this would only work on the server it was written for. There
is a simple, nearly one-line fix for this to handle cross-site work, but
I don't recall the specifics right now. I have client-side code calling
it (for now) on my work website (http://www.genomics.purdue.edu/~jacoby/).
---8<--------------------
#!/usr/bin/perl
use 5.010 ;
use strict ;
use warnings ;
use CGI ;
use CGI::Carp qw( fatalsToBrowser ) ;
use Data::Dumper ;
use JSON ;
use LWP::UserAgent ;
my $cgi = new CGI ;
my $params ;
%$params = map { $_, $cgi->param( $_ ) } $cgi->param() ;
say 'content-type: text/plain' ;
say '' ;
my $x = $params->{ x } ;
my $y = $params->{ y } ;
$x =~ s/[A-Za-z\s]//gmx ;
$y =~ s/[A-Za-z\s]//gmx ;
$x = $x eq '' ? 2 : $x ;
$y = $y eq '' ? 2 : $y ;
my $out ;
$out->{ x } = $x ;
$out->{ y } = $y ;
$out->{ result } = $x + $y ;
if ( $params->{ d } ) {
say Dumper $out ;
}
else {
say JSON::to_json( $out ) ;
}
exit ;
---8<--------------------
--
Dave Jacoby Address: WSLR S049
Code Maker Mail: jacoby at purdue.edu
Purdue University Phone: 765.49.67368
More information about the Purdue-pm
mailing list