Tatsuhiko Miyagawa's Blog

Plack middleware

September 18, 2009

Middleware is some great (but sometimes abused) features in Python’s WSGI and Ruby’s Rack. HTTP::Engine also had this middleware concept and had some great “plugins”. So it’s time to write the new middleware framework for PSGI and Plack.

In PSGI, middleware is just a PSGI application thatdoes the both application and server side. It takes the $env hash like application does and then runs the original application like a server does, and then return the response. Middleware can do pre-processing on the $env hash or do post-processing on $env or $res. Example middleware would be doing some X-Sendfile work, normalizing proxy IP address using X-Forwarded-For, map static files to /static, catch the runtime error and display a beautiful stack trace or profile the runtime requests using profilers like NYTProf.

Today I made a middleware branch on Plack repo so writing and enabling middleware is now extremely easy:

use Plack::Middleware qw( Foo Bar Baz );
use Plack::Builder;

my $app = sub { ... };
builder {
 enable Plack::Middleware::Foo;
 enable Plack::Middleware::Bar %options;
 enable Plack::Middleware::Foo %options;
 $app
}

This syntax sugar is just cloned from Rack::Builder, and it looks really easy and intuitive. If you don’t like the DSL you can also use ->wrap(@options, $app) to do the same.