CGI::A...spatch(3pm)
CGI::A...spatch(3pm) β User Contributed Perl Documentation. Okay bestie, this page is literally about CGI::Application::Dispatch, and we're gonna get into it. π
β¨ NAME β¨
CGI::Application::Dispatch - Dispatch requests to CGI::Application based objects π
πΈ SYNOPSIS πΈ
Okay so here's the vibe, bestie. You can run this out of the box or with a dispatch table. Both are iconic. β¨
π Out of Box π
Under mod_perl:
<Location /app>
SetHandler perl-script
PerlHandler CGI::Application::Dispatch
</Location>
Under normal cgi:
This would be the instance script for your application, such as /cgi-bin/dispatch.cgi:
#!/usr/bin/perl
use FindBin::Real 'Bin';
use lib Bin() . '/../../rel/path/to/my/perllib';
use CGI::Application::Dispatch;
CGI::Application::Dispatch->dispatch();
π¦ With a dispatch table π¦
package MyApp::Dispatch;
use base 'CGI::Application::Dispatch';
sub dispatch_args {
return {
prefix => 'MyApp',
table => [
'' => { app => 'Welcome', rm => 'start' },
':app/:rm' => { },
'admin/:app/:rm' => { prefix => 'MyApp::Admin' },
],
};
}
Under mod_perl:
<Location /app>
SetHandler perl-script
PerlHandler MyApp::Dispatch
</Location>
Under normal cgi:
This would be the instance script for your application, such as /cgi-bin/dispatch.cgi:
#!/usr/bin/perl
use FindBin::Real 'Bin';
use lib Bin() . '/../../rel/path/to/my/perllib';
use MyApp::Dispatch;
MyApp::Dispatch->dispatch();
π DESCRIPTION π
Okay so this module provides a way β as a mod_perl handler or running under vanilla CGI β to look at the path (as returned by dispatch_path) of the incoming request, parse off the desired module and its run mode, create an instance of that module and run it. Periodt. π
It currently supports both generations of mod_perl (1.x and 2.x). Although, for simplicity, all examples involving Apache configuration and mod_perl code will be shown using mod_perl 1.x. This may change as mp2 usage increases. π
It will translate a URI like this (under mod_perl):
/app/module_name/run_mode
or this (vanilla cgi)
/app/index.cgi/module_name/run_mode
into something that will be functionally similar to this
my $app = Module::Name->new(..);
$app->mode_param(sub {'run_mode'}); #this will set the run mode
β¨ METHODS β¨
π
dispatch(%args)
Okay bestie, this is THE main character method β the one that does all the work when dispatch happens. Even when you're running under mod_perl, the handler method is just quietly using this one under the hood. It's giving effortlessly powerful. π«Ά
#!/usr/bin/perl
use strict;
use CGI::Application::Dispatch;
CGI::Application::Dispatch->dispatch(
prefix => 'MyApp',
default => 'module_name',
);
This method accepts the following name value pairs:
defaultβ give it a value to use for the path when there's, like, no path available. Which happens when the default page gets picked (think:"/"). The fallback bestie. πΈprefixβ this option sets the string that gets prepended to the name of the application module before it's loaded and created. So let's say you have our earlier example request of
/app/index.cgi/module_name/run_mode
By default that would load and create a module named 'Module::Name'. But say all your app-specific modules live under the 'My' namespace β set this option to 'My' and it'll load the 'My::Module::Name' application module instead. Glow up via namespace. β¨
args_to_newβ this is a hash of arguments that get passed into thenew()constructor of the application.tableβ in most cases, just using Dispatch withdefaultandprefixis enough to simplify your application and your URLs, but there are so many cases where you want more power. Enter: the dispatch table. And because this table can get a little complicated, there's a whole section dedicated to it. Go peek at the DISPATCH TABLE section, iykyk. πdebugβ set it to a true value and this module will send debugging output toSTDERR. Off by default. (Keep it off in prod, bestie, fr fr. π)error_documentβ this string is similar to the ApacheErrorDocumentdirective. If this value isn't present, then Dispatch will return aNOT FOUNDerror β either to the browser with a simple hardcoded message (under CGI) or to Apache (under mod_perl).
This value can be one of the following:
- A string with an error message β if it starts with a single double-quote character (
"). That double-quote character will be trimmed from the final output. - A file with the content of the error document β if it starts with a less-than sign (
<). The first character will be excluded as well. The path of this file should be relative to the serverDOCUMENT_ROOT. - A URI to which the application will be redirected β if no leading
"or<is found.
Custom messages will be displayed in non mod_perl environments only. (Under mod_perl, please use the ErrorDocument directive in your Apache configuration files.) This value can contain a %s placeholder for the sprintf Perl function. That placeholder gets replaced with the numeric HTTP error code. Currently CGI::Application::Dispatch uses three HTTP errors:
400 Bad Requestβ if there are invalid characters in the module name (parameter:app) or the runmode name (parameter:rm).404 Not Foundβ when the path doesn't match anything in the DISPATCH TABLE, or the module couldn't be found in@INC, or the run mode didn't exist.500 Internal Server Errorβ if an application error occurs.
Examples of using error_document (assume error 404 has been returned):
# return in browser 'Opss... HTTP Error #404'
error_document => '"Opss... HTTP Error #%s'
# return contents of file $ENV{DOCUMENT_ROOT}/errors/error404.html
error_document => '</errors/error%s.html'
# internal redirect to /errors/error404.html
error_document => '/errors/error%s.html'
# external redirect to
# http://host.domain/cgi-bin/errors.cgi?error=404
error_document => 'http://host.domain/cgi-bin/errors.cgi?error=%s'
auto_restβ this tells Dispatch that you're using REST by default and that you care about which HTTP method is being used. Dispatch will append the HTTP method name (upper case by default) to the run mode that's determined after finding the appropriate dispatch rule. So aGETrequest that translates intoMyApp::Module->foobecomesMyApp::Module->foo_GET. REST-coded behavior, slay. π₯
This can be overridden on a per-rule basis in a custom dispatch table.
auto_rest_lcβ in combination withauto_rest, this tells Dispatch that you prefer lower cased HTTP method names. So instead offoo_POSTandfoo_GETyou'll havefoo_postandfoo_get. Lowercase girls rise. π
π¦ dispatch_path()
This method returns the path that's going to be processed.
By default it returns the value of $ENV{PATH_INFO} (or $r->path_info under mod_perl) which should work for most cases. It also allows subclasses the ability to override the value if they need to do something more specific. Customize away, bestie. π
β handler()
This method exists so that this module can be run as a mod_perl handler. When it creates the application module, it passes the $r argument into the PARAMS hash of new().
<Location /app>
SetHandler perl-script
PerlHandler CGI::Application::Dispatch
PerlSetVar CGIAPP_DISPATCH_PREFIX MyApp
PerlSetVar CGIAPP_DISPATCH_DEFAULT /module_name
</Location>
The above example would tell Apache that any URL beginning with /app will be handled by CGI::Application::Dispatch. It also sets the prefix used to create the application module to 'MyApp', and it tells CGI::Application::Dispatch that it shouldn't set the run mode β but that it will be determined by the application module as usual (through the query string). It also sets a default application module to be used if there's no path. So a URL of "/app/module_name" would create an instance of MyApp::Module::Name. So iconic. π
Using this method will add the Apache->request object to your application's PARAMS as 'r'.
# inside your app
my $request = $self->param('r');
If you need more customization than can be accomplished with just prefix and default, then it would be best to just subclass CGI::Application::Dispatch and override dispatch_args, since handler() uses dispatch to do the heavy lifting. (Let the main method carry, honestly. π
)
package MyApp::Dispatch;
use base 'CGI::Application::Dispatch';
sub dispatch_args {
return {
prefix => 'MyApp',
table => [
'' => { app => 'Welcome', rm => 'start' },
':app/:rm' => { },
'admin/:app/:rm' => { prefix => 'MyApp::Admin' },
],
args_to_new => {
PARAMS => {
foo => 'bar',
baz => 'bam',
},
}
};
}
1;
And then in your httpd.conf:
<Location /app>
SetHandler perl-script
PerlHandler MyApp::Dispatch
</Location>
π§ dispatch_args()
Returns a hashref of args that will be passed to dispatch(). By default it returns the following structure:
{
prefix => '',
args_to_new => {},
table => [
':app' => {},
':app/:rm' => {},
],
}
This is the perfect place to override when you're creating a subclass and want to provide a richer dispatch table. Chef's kiss opportunity, no cap. π
When called, it receives 1 argument, which is a reference to the hash of args passed into dispatch.
πΈ translate_module_name($input)
This method is used to control how the module name is translated from the matching section of the path (see "Path Parsing"). The main reason this method exists is so it can be overridden if it doesn't do exactly what you want. Very considerate of it, honestly. π«Ά
The following transformations are performed on the input:
- The text is split on
'_'s (underscores) and each word has its first letter capitalized. The words are then joined back together and each instance of an underscore is replaced by'::'. - The text is split on
'-'s (hyphens) and each word has its first letter capitalized. The words are then joined back together and each instance of a hyphen removed.
Here are some examples to make it even clearer:
module_name => Module::Name
module-name => ModuleName
admin_top-scores => Admin::TopScores
π require_module($module_name)
This class method is used internally by CGI::Application::Dispatch to take a module name (supplied by get_module_name) and require it in a secure fashion. It's provided as a public class method so that if you override other functionality of this module, you can still safely require user specified modules. And if there are any problems requiring the named module, then we will "croak". π€
CGI::Application::Dispatch->require_module('MyApp::Module::Name');
π DISPATCH TABLE π
okay bestie, sometimes the fastest way to explain a thing is just to show you the thing, so here you go:
CGI::Application::Dispatch->dispatch(
prefix => 'MyApp',
args_to_new => {
TMPL_PATH => 'myapp/templates'
},
table => [
'' => { app => 'Blog', rm => 'recent'},
'posts/:category' => { app => 'Blog', rm => 'posts' },
':app/:rm/:id' => { app => 'Blog' },
'date/:year/:month?/:day?' => {
app => 'Blog',
rm => 'by_date',
args_to_new => { TMPL_PATH => "events/" },
},
]
);
so first things first: this call to dispatch sets the prefix and sneaks a "TMPL_PATH" into args_to_new. and then it sets the table. that's it, that's the whole vibe β¨
π VOCABULARY π
just so we're all on the same page about what we're even talking about here...
A table is an array where the elements are grouped as pairs β kinda like a hash's key-value pairs, except it's an array so that the order is preserved. the first element of each pair is called a "rule". the second element in the pair is called the rule's "arg list". inside a rule there are slashes /. any set of characters between slashes is called a "token". iykyk π
π¦ URL MATCHING π¦
when a URL rolls in, Dispatch tries to match it against each rule in the table in the order in which the rules are given. first one to match wins. no cap, order literally matters.
a rule consists of slashes and tokens. a token can be one of the following types:
- literal β any token that does not start with a colon (
":") is taken to be a literal string and has to appear exactly as-is in the URL in order to match. in the rule
'posts/:category'
"posts" is a literal token. it said what it said.
- variable β any token that begins with a colon (
":") is a variable token. these are just wild-card placeholders in the rule that will match anything in the URL that isn't a slash. you can refer back to these variables later using the$self->parammechanism. in the rule
'posts/:category'
":category" is a variable token. if the URL matched this rule, then you could grab the value of that token from inside your application like so:
my $category = $self->param('category');
now, there are some variable tokens that are special, and these ones let you customize the dispatching even more π
:appβ this is the module name of the application. the value of this token gets sent to thetranslate_module_namemethod and then prefixed with the prefix if there is one.:rmβ this is the run mode of the application. the value of this token will be the actual name of the run mode used. the run mode can be optional, as noted below. example:
/foo/:rm?
if no run mode is found, it'll default to using the "start_mode()", just like invoking CGI::Application directly. both of these URLs would end up dispatching to the start mode associated with /foo:
/foo/
/foo
- optional-variable β any token that begins with a colon (
":") and ends with a question mark (<?>) is considered optional. if the rest of the URL matches the rest of the rule, then it literally doesn't matter whether it contains this token or not. bestie, it's best to only put optional-variable tokens at the end of your rule. in the rule
'date/:year/:month?/:day?'
":month?" and ":day?" are optional-variable tokens.
just like with variable tokens, optional-variable tokens' values can also be retrieved by the application β if they existed in the URL, that is.
if( defined $self->param('month') ) {
...
}
- wildcard β the wildcard token
"*"allows for partial matches. the token MUST appear at the end of the rule.
'posts/list/*'
by default, the "dispatch_url_remainder" param is set to the remainder of the URL matched by the *. you can change the name of that param by setting the "*" argument in the "ARG LIST".
'posts/list/*' => { '*' => 'post_list_filter' }
- method β you can also dispatch based on HTTP method. this is similar to using
auto_restbut it offers more fine-grained control. you include the method (case insensitive) at the end of the rule and wrap it in square brackets.
':app/news[post]' => { rm => 'add_news' },
':app/news[get]' => { rm => 'news' },
':app/news[delete]' => { rm => 'delete_news' },
the main reason we don't use regular expressions for dispatch rules is that regular expressions provide no mechanism for named back references, like variable tokens do. periodt.
πΈ ARG LIST πΈ
each rule can have an accompanying arg-list. this arg list can contain special arguments that override something set higher up in dispatch for this particular URL, or it can just have additional args passed that'll be available in $self->param(). π«Ά
for instance, if you want to override the prefix for one specific rule, then you can absolutely do that:
'admin/:app/:rm' => { prefix => 'MyApp::Admin' },
π Path Parsing π
this section is gonna describe how the application module and the run mode get determined from the path when there's no "DISPATCH TABLE" present, plus what options you've got to customize the whole process. the value for the path to be parsed comes from the dispatch_path method, which by default uses the "PATH_INFO" environment variable. β¨
π Getting the module name π
to get the name of the application module, the path gets split on slashes ("/"). the second element of the returned list (the first one is empty) is used to create the application module. so if we have a path of
/module_name/mode1
then the string 'module_name' is what gets used. this is passed through the translate_module_name method. then if there's a "prefix" (and there really should always be a prefix), it gets added to the beginning of this new module name with a double colon "::" separating the two.
if you don't like the exact way this is done, don't fret β you've got a couple of options, bestie. first, you can specify a "DISPATCH TABLE", which is way more powerful and flexible (in fact this default behavior is actually implemented internally with a dispatch table). or, if you want something a lil simpler, you can just subclass and extend the translate_module_name method. easy. π
π§ Getting the run mode π§
just like the module name is retrieved from splitting the path on slashes, so is the run mode. only instead of using the second element of the resulting list, we use the third one as the run mode. so, using the same example, if we have a path of
/module_name/mode2
then the string 'mode2' is used as the run mode.
β MISC NOTES β
- CGI query strings β CGI query strings are unaffected by the use of
"PATH_INFO"to obtain the module name and run mode. this means that any other modules you use to get access to your query arguments (ie, CGI, Apache::Request) should not be affected. but heads up: since the run mode may be determined by CGI::Application::Dispatch, having a query argument named'rm'will be ignored by your application module. π
π₯ CLEAN URLS WITH MOD_REWRITE π₯
with a dispatch script, you can get fairly clean URLs like this:
/cgi-bin/dispatch.cgi/module_name/run_mode
but ngl, including "/cgi-bin/dispatch.cgi" in every URL doesn't add any value to the URL, so it's nice to remove it. this is easily done if you're using the Apache web server with "mod_rewrite" available. adding the following to a .htaccess file would let you simply use:
/module_name/run_mode
and if you have problems with mod_rewrite, turn on debugging to see exactly what's happening:
RewriteLog /home/project/logs/alpha-rewrite.log
RewriteLogLevel 9
π mod_rewrite related code in the dispatch script. π
this seemed necessary to put in the dispatch script to make mod_rewrite happy. perhaps it's specific to using "RewriteBase".
# mod_rewrite alters the PATH_INFO by turning it into a file system path,
# so we repair it.
$ENV{PATH_INFO} =~ s/^$ENV{DOCUMENT_ROOT}// if defined $ENV{PATH_INFO};
π Simple Apache Example π
RewriteEngine On
# You may want to change the base if you are using the dispatcher within a
# specific directory.
RewriteBase /
# If an actual file or directory is requested, serve directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Otherwise, pass everything through to the dispatcher
RewriteRule ^(.*)$ /cgi-bin/dispatch.cgi/$1 [L,QSA]
π More complex rewrite: dispatching "/" and multiple developers π
here's a more complex example that dispatches "/", which would otherwise be treated as a directory, and also supports multiple developer directories, so "/~mark" has its own separate dispatching system beneath it. multi-dev slay.
note that order matters here! theLocationblock for"/"needs to come before the user blocks.
<Location />
RewriteEngine On
RewriteBase /
# Run "/" through the dispatcher
RewriteRule ^home/project/www/$ /cgi-bin/dispatch.cgi [L,QSA]
# Don't apply this rule to the users sub directories.
RewriteCond %{REQUEST_URI} !^/~.*$
# If an actual file or directory is requested, serve directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Otherwise, pass everything through to the dispatcher
RewriteRule ^(.*)$ /cgi-bin/dispatch.cgi/$1 [L,QSA]
</Location>
<Location /~mark>
RewriteEngine On
RewriteBase /~mark
# Run "/" through the dispatcher
RewriteRule ^/home/mark/www/$ /~mark/cgi-bin/dispatch.cgi [L,QSA]
# Otherwise, if an actual file or directory is requested,
# serve directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Otherwise, pass everything through to the dispatcher
RewriteRule ^(.*)$ /~mark/cgi-bin/dispatch.cgi/$1 [L,QSA]
# These examples may also be helpful, but are unrelated to dispatching.
SetEnv DEVMODE mark
SetEnv PERL5LIB /home/mark/perllib:/home/mark/config
ErrorDocument 404 /~mark/errdocs/404.html
ErrorDocument 500 /~mark/errdocs/500.html
</Location>
π SUBCLASSING π
while Dispatch tries to be flexible, it won't be able to do everything that people want. hopefully we've made it flexible enough that if it doesn't do The Right Thing, you can easily subclass it. go off, make it yours π β¨
π AUTHOR π
Michael Peters <mpeters@plusthree.com>
thanks to Plus Three, LP (http://www.plusthree.com) for sponsoring my work on this module π«Ά
π COMMUNITY π
okay bestie, this module is not a solo act β it's part of the bigger CGI::Application community, a whole little ecosystem fr fr. so if you've got questions, comments, or just wanna vibe with other people who also type $self-> in their dreams, come join us on the cgiapp mailing list π β all you gotta do is send a blank message to:
cgiapp-subscribe@lists.erlbaum.net
blank message, that's it, no subject, no essay, just vibes and an empty inbox contribution. and there's also a community wiki hanging out at <http://www.cgi-app.org/> β go peek, it's giving shared knowledge, it's giving collaboration π
π¦ SOURCE CODE REPOSITORY π¦
there's a public source code repository for this project and it lives right here, bestie:
http://code.google.com/p/cgi-app-modules/source/checkout
go forth and clone, no gatekeeping here π«Ά
π CONTRIBUTORS π
these are the absolute icons who made this happen, the main characters, the ones who said "not me letting this module be mid" and fixed it. show them respect β¨
- Shawn Sorichetti
- Timothy Appnel
- dsteinbrunner
- ZACKSE
- Stew Heckenberg
- Drew Taylor
<drew@drewtaylor.com> - James Freeman
<james.freeman@smartsurf.org> - Michael Graham
<magog@the-wire.com> - Cees Hek
<ceeshek@gmail.com> - Mark Stosberg
<mark@summersault.com> - Viacheslav Sheveliov
<slavash@aha.ru>
π¨ SECURITY π¨
okay so this is the part where we get serious, no jokes, listen up π
since C::A::Dispatch will dynamically choose which modules to use as the content generators, it may give someone the ability to execute random modules on your system if those modules can be found in you path. like, random ones. not the ones you meant. not the ones you wrote. random ones π
and yeah, of course those modules would have to behave like CGI::Application based modules for it to even work, but that still opens up the door more than most want. the door is open. the door should not be open. π
the fix: this should only be a problem if you don't use a prefix. by using this option you are only allowing Dispatch to pick from a namespace of modules to run. so USE THE PREFIX, bestie, protect your server, protect your peace π
π SEE ALSO π
go read these too, they're the extended universe:
CGI::ApplicationApache::Dispatch
π COPYRIGHT & LICENSE π
Copyright Michael Peters and Mark Stosberg 2008, all rights reserved.
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
and that's the whole page, bestie!! we did it π₯³ this was CGI::A...spatch(3pm), documented by the User Contributed Perl Documentation crew, generated with perl v5.34.0 and dated 2022-06-09 β so if you're reading this and the date feels ancient, that's because it is, and honestly? iconic behavior. go write some dispatch tables and slay π
π¦πΈ
π¦ where this page comes from
- debian bookworm: libcgi-application-dispatch-perl 3.12-3 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- debian trixie: libcgi-application-dispatch-perl 3.12-3 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu noble: libcgi-application-dispatch-perl 3.12-3 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu resolute: libcgi-application-dispatch-perl 3.12-3 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu stonking: libcgi-application-dispatch-perl 3.12-3 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms