Perl Programming/PSGI

From Wikibooks, open books for an open world
< Perl Programming
Jump to: navigation, search

PSGI is an interface between Perl web applications and web servers. PSGI is inspired by Python's WSGI and Ruby's Rack. The specification was discussed in YAPC::Asia 2009, and the reference implementation Plack, has been developed by Tatsuhiko Miyagawa.

The concept of PSGI can maybe describe as "The middle layer of everything". It extends and enhances the old CGI standard such that web applications on top of the same PSGI layer can share certain common data, such as http authentication, database connection handle and session. While those may have been implemented as Apache modules over past years, PSGI specification makes it possible and easy to develop middle-wares for all applications and all front-end servers.

The core specification of PSGI is very simple. A PSGI application, is a Perl subroutine, that takes exactly one argument, the environment and returns an array reference of exactly three values. The status code, the response headers, and the response body. Here's an example of a "Hello World" PSGI application:

 sub app {
     my $env = shift;
     return [
         '200',
         [ 'Content-Type' => 'text/plain' ],
         [ "Hello World" ]
     ];
 }

The $env is a hashref that contain environment variables. It includes the values in the %ENV hash, but there are more PSGI-specific values inside. Developers writing PSGI-based web applications should not access %ENV hash directly.