CGI::A...::PSGI(3pm)

πŸ“¦
version 3.12 Β· 4 versions
, in debian bookworm, debian trixie, ubuntu noble, ubuntu resolute, ubuntu stonking

πŸ’– CGI::Application::Dispatch::PSGI β€” the manual page, but make it make sense πŸ’–

User Contributed Perl Documentation Β· CGI::A...::PSGI(3pm)


✨ NAME ✨

CGI::Application::Dispatch::PSGI β€” bestie, it dispatches requests to your CGI::Application-based objects, but make it PSGI. πŸ¦‹


🌸 SYNOPSIS 🌸

πŸŽ€ Out of Box

Under mod_perl:

# change "Apache1" to "Apache2" as needed.

<Location />
SetHandler perl-script
PerlHandler Plack::Handler::Apache1
PerlSetVar psgi_app /path/to/app.psgi
</Location>

<Perl>
use Plack::Handler::Apache1;
Plack::Handler::Apache1->preload("/path/to/app.psgi");
</Perl>

Under CGI:

This would be the instance script for your application, such as /cgi-bin/dispatch.cgi:

### in your dispatch.psgi:
# ( in a persistent environment, use FindBin::Real instead. )
use FindBin 'Bin';
use lib "$Bin/../perllib";
use Your::Application::Dispatch;
Your::Application::Dispatch->as_psgi;

### In Your::Application::Dispatch;
package Your::Application::Dispatch;
use base 'CGI::Application::Dispatch::PSGI';

πŸ“ With a dispatch table

package MyApp::Dispatch;
use base 'CGI::Application::Dispatch::PSGI';

sub dispatch_args {
    return {
        prefix  => 'MyApp',
        table   => [
            ''                => { app => 'Welcome', rm => 'start' },
            ':app/:rm'        => { },
            'admin/:app/:rm'  => { prefix   => 'MyApp::Admin' },
        ],
    };
}

The .psgi file is constructed as above. πŸ’…

🧚 With a custom query object

If you want to supply your own PSGI object, something like this in your .psgi file will work:

sub {
    my $env = shift;
    my $app = CGI::Application::Dispatch::PSGI->as_psgi(
        table => [
            '/:rm'    =>    { app => 'TestApp' }
        ],
        args_to_new => {
            QUERY    => CGI::PSGI->new($env)
        }
    );
    return $app->($env);
}

πŸ‘‘ DESCRIPTION πŸ‘‘

Okay so here's the whole vibe: this module gives you a way to look at the path of the incoming request β€” specifically the one that comes back from "$env->{PATH_INFO}" β€” parse off the module you want and its run mode, create an instance of that module, and run it. Main character energy, honestly. 🌈

It will translate a URI like this (in a persistent environment)

/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 πŸ’…

⭐ as_psgi(%args)

This is the primary method used during dispatch.

#!/usr/bin/perl
use strict;
use CGI::Application::Dispatch::PSGI;

CGI::Application::Dispatch::PSGI->as_psgi(
    prefix  => 'MyApp',
    default => 'module_name',
);

This method accepts the following name value pairs:

  • default β€” Specify a value to use for the path if one is not available. This could be the case if the default page is selected (eg: "/"). 🫢
  • prefix β€” This option will set the string that will be prepended to the name of the application module before it is loaded and created. So to use our previous example request of
/app/index.cgi/module_name/run_mode

This would by default load and create a module named 'Module::Name'. But let's say that you have all of your application specific modules under the 'My' namespace. If you set this option to 'My' then it would instead load the 'My::Module::Name' application module instead. ✨

  • args_to_new β€” This is a hash of arguments that are passed into the "new()" constructor of the application.
  • table β€” In most cases, simply using Dispatch with the "default" and "prefix" is enough to simplify your application and your URLs, but there are many cases where you want more power. Enter the dispatch table. Since this table can be slightly complicated, a whole section exists on its use. Please see the "DISPATCH TABLE" section. πŸ‘‘
  • debug β€” Set to a true value to send debugging output for this module to STDERR. Off by default.
  • auto_rest β€” This tells Dispatch that you are 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 is determined after finding the appropriate dispatch rule. So a GET request that translates into "MyApp::Module->foo" will become "MyApp::Module->foo_GET". πŸ”₯

This can be overridden on a per-rule basis in a custom dispatch table.

  • auto_rest_lc β€” In combinaion with auto_rest this tells Dispatch that you prefer lower cased HTTP method names. So instead of "foo_POST" and "foo_GET" you'll have "foo_post" and "foo_get". πŸ’œ

πŸ¦‹ dispatch_args()

Returns a hashref of args that will be passed to dispatch(). It will return the following structure by default.

{
    prefix      => '',
    args_to_new => {},
    table       => [
        ':app'      => {},
        ':app/:rm'  => {},
    ],
}

This is the perfect place to override when creating a subclass to provide a richer dispatch table. 🌸

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 that this method exists is so that it can be overridden if it doesn't do exactly what you want.

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 to take a module name (supplied by get_module_name) and require it in a secure fashion. It is provided as a public class method so that if you override other functionality of this module, you can still safely require user specified modules. If there are any problems requiring the named module, then we will "croak". πŸ’€

CGI::Application::Dispatch::PSGI->require_module('MyApp::Module::Name');

πŸŽ€ DISPATCH TABLE πŸŽ€

Sometimes a girl just needs an example, so here's one bestie, feast your eyes:

CGI::Application::Dispatch::PSGI->as_psgi(
  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 like, first this call to as_psgi sets the prefix and passes a "TMPL_PATH" into args_to_new. Then it sets the table. Simple as that, no cap. πŸ’…


🌸 VOCABULARY 🌸

Okay we need to be on the same page about the words here, so let's define the vibes:

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 order stays intact, which is the whole point. 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.


✨ URL MATCHING ✨

When a URL comes 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, periodt. πŸ‘‘

A rule consists of slashes and tokens. A token can be one of the following types:

literal

Any token which does not start with a colon (":") is taken to be a literal string and must appear exactly as-is in the URL in order to match. In the rule

'posts/:category'

"posts" is a literal token.

variable

Any token which begins with a colon (":") is a variable token. These are just wild-card place holders in the rule that will match anything in the URL that isn't a slash. You can refer to these variables later by using the "$self->param" mechanism. In the rule

'posts/:category'

:category is a variable token. If the URL matched this rule, then you could get the value of that token from within your application like so:

my $category = $self->param('category');

There are some variable tokens which are special. These can be used to further customize the dispatching.

:app

This is the module name of the application. The value of this token will be sent to the translate_module_name method 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 will 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 which 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 doesn't matter whether it contains this token or not. Pro tip from me to you: it's best to only include 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. πŸ’–

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 *. The name of the param can be changed by setting "*" 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_rest but offers more fine grained control. You include the method (case insensitive) at the end of the rule and enclose it in square brackets.

':app/news[post]'   => { rm => 'add_news'    },
':app/news[get]'    => { rm => 'news'        },
':app/news[delete]' => { rm => 'delete_news' },

The main reason that we don't use regular expressions for dispatch rules is that regular expressions provide no mechanism for named back references, like variable tokens do. iykyk 🧚


πŸ’œ 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 just have additional args passed available in "$self->param()".

For instance, if you want to override prefix for a specific rule, then you can do so.

'admin/:app/:rm' => { prefix => 'MyApp::Admin' },

πŸ¦‹ Path Parsing πŸ¦‹

This section will describe how the application module and run mode are determined from the path if no "DISPATCH TABLE" is present, and what options you have to customize the process. The value for the path to be parsed is retrieved from "$env->{PATH_INFO}".

🌈 Getting the module name 🌈

To get the name of the application module the path is split on slashes ("/"). The second element of the returned list (the first 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 used. This is passed through the translate_module_name method. Then if there is a "prefix" (and there should always be a prefix) it is added to the beginning of this new module name with a double colon "::" separating the two.

If you don't like the exact way that this is done, don't fret bestie, you do have a couple of options. First, you can specify a "DISPATCH TABLE" which is much more powerful and flexible (in fact this default behavior is actually implemented internally with a dispatch table). Or if you want something a little simpler, you can simply subclass and extend the translate_module_name method. 🫢

⭐ 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 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.


😭 Exception Handling 😭

A CGI::Application object can throw an exception up to "CGI::Application::Dispatch::PSGI" if no "error_mode()" is implemented or if the error_mode itself throws an exception. In these cases we generally return a generic "500" response, and log some details for the developer with a warning.

However, we will check to see if the exception thrown is an HTTP::Exception object. If that's the case, we will rethrow it, and you can handle it yourself using something like Plack::Middleware::HTTPExceptions.


πŸ‘‘ 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 argument (ie, CGI, Apache::Request) should not be affected. But, since the run mode may be determined by CGI::Application::Dispatch::PSGI having a query argument named 'rm' will be ignored by your application module. πŸ™ˆ


πŸ”₯ CLEAN URLS WITH MOD_REWRITE πŸ”₯

With a dispatch script, you can fairly clean URLS like this:

 /cgi-bin/dispatch.cgi/module_name/run_mode

However, 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 are using the Apache web server with "mod_rewrite" available. Adding the following to a ".htaccess" file would allow you to simply use:

 /module_name/run_mode

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

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 is 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.

Note that order matters here! The Location block 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 🧬

So like, Dispatch tries to be flexible, bestie, but it's never gonna do every single thing everyone on earth wants. Hopefully we made it flexible enough that if it doesn't do The Right Thing, you can just subclass it and go off. πŸ’…


πŸ‘‘ AUTHORS πŸ‘‘

Mark Stosberg <mark@summersault.com>

Heavily based on CGI::Application::Dispatch, written by Michael Peters <mpeters@plusthree.com> and others


🫢 COMMUNITY 🫢

This module is part of the bigger CGI::Application community, and honestly the vibes are immaculate. If you've got questions or comments about this module, come hang out with us on the cgiapp mailing list β€” just send a blank message to cgiapp-subscribe@lists.erlbaum.net and you're in. 🌸

There's also a community wiki over at http://www.cgi-app.org/ if that's more your thing. ✨


πŸ“¦ SOURCE CODE REPOSITORY πŸ“¦

A public source code repository for this project lives right here:

https://github.com/markstos/CGI--Application--Dispatch

Go peek. Go contribute. Go be the main character. 🌈


πŸ”’ SECURITY πŸ”’

Okay so real talk, this one matters. Since C::A::Dispatch::PSGI will dynamically choose which modules to use as the content generators, it might literally hand someone the ability to execute random modules on your system β€” if those modules can be found in your path. 😭

Now, those modules would have to behave like CGI::Application based modules, so it's not total chaos, but it still opens up the door way more than most people want. This should only be a problem if you don't use a prefix. By using this option you're only letting Dispatch pick from a namespace of modules to run. So use it. Periodt. πŸ‘‘

πŸ” Backwards Compatibility πŸ”

Versions 0.2 and earlier of this module injected the as_psgi method into CGI::Application::Dispatch, which created a syntax like this:

### in your dispatch.psgi:
use Your::Application::Dispatch;
use CGI::Application::Dispatch::PSGI;
Your::Application::Dispatch->as_psgi;

### In Your::Application::Dispatch;
use base 'CGI::Application::Dispatch::PSGI';

In the current design, the as_pgsi method is directly in this module, so you've gotta change a couple of lines of code:

### in your dispatch.psgi:
use Your::Application::Dispatch;
Your::Application::Dispatch->as_psgi;

### In Your::Application::Dispatch;
use base 'CGI::Application::Dispatch::PSGI';

Tiny glow-up, huge difference. πŸ’–


πŸ¦‹ Differences with CGI::Application::Dispatch πŸ¦‹

dispatch()

Use as_psgi() instead.

Also note that the error_document key is not supported here. Use the Plack::Middleware::ErrorDocument or another PSGI solution instead. πŸ™ˆ

dispatch_path()

The dispatch_path() method is not supported. The alternative is to reference $env->{PATH_INFO}, which is available per the PSGI spec.

handler()

This used to provide an Apache-specific handler. Other PSGI components like Plack::Handler::Apache2 provide Apache handlers now instead.

_http_method()

This method has been eliminated. Check $env->{REQUEST_METHOD} directly instead. πŸ‘€

_parse_path()

The private _parse_path() method now accepts an additional argument, the PSGI $env hash.

_run_app()

The private _run_app() method now accepts an additional argument, the PSGI $env hash.

_r()

This method has been eliminated. It does not apply in PSGI. Gone. Not coming back. πŸ’€


πŸ‘€ SEE ALSO πŸ‘€

CGI::Application, Apache::Dispatch


Copyright Michael Peters and Mark Stosberg 2008-2010, all rights reserved.

This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.


okay bestie that's the whole page, you made it to the end, so proud of you πŸ₯ΉπŸ’– this was perl v5.34.0, dated 2022-06-09, and no cap it's giving iconic manual page energy. go forth and dispatch. πŸŽ€βœ¨

πŸ“¦ where this page comes from