This code is handling and routing CGI requests based on the path (the bit that comes after the script name in a URL). It seems well thought out and covers all possible error cases. However, it is written in a style which is alien to me, and I think most monks here would reccommend against following this style.
Let's say we call the script like this:
http://localhost/script.cgi/=
The request method is GET, and the path is "/=". You get the path by calling CGI method
$q->path_info
The script will call a series of subroutines until it finds a match for the request method and path. In the
eval{} block you see this series of calls. One of them is:
GET qr{^/=$} => sub {
print $q->header('text/html');
print $q->h1('REST API Documentation');
print $q->p('Here is a list of what you can do:');
This could be written as:
my $regex = qr{^/=$};
my $coderef = sub {
print $q->header('text/html');
# etc.
};
GET( $regex, $coderef );
So it sends off the $regex and the $coderef to the
GET() subroutine, which then checks if the request method is 'GET' and if the path matches the regular expression. In our case the path "/=" does match the regular expression
{^/=$}, so it then calls the subroutine referenced in $coderef and then exits:
$code->();
exit;
If the regex didn't match it would go on to the next test in the series, which would try to match the path to the regex
{^/=/model/book/id/([\d-]+)$}
GET qr{^/=/model/book/id/([\d-]+)$} => sub {
my $id = $1;
# etc.
If we were to call the script with this URL
http://localhost/script.cgi/=/model/book/id/10566
then this regex would match, the code ref will be called and $id will contain the value "10566". If it didn't match the script will continue to test all the possible GET, POST, PUT and DELETE methods in the eval block until it finds a match. If it doesn't find one it returns a 404 Not Found response.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.