Exploring Plack Middlewares

Sponsored · Ship Features Fearlessly Turn features on and off without deploys. Used by thousands of Ruby developers. →

Exploring Plack Middlewares

My talk at German Perl Workshop 2013
Plack is Rack analogue for Perl programming language

Oleg Komarov

March 14, 2013

Annual Pro sale · Save $30

Have presentations of your own?

Share with private links, password protection, and more control over your work.

Transcript

31 slides
  1. PSGI Perl Web Server Gateway Interface https://metacpan.org/module/PSGI web servers PSGI

    server/application container provides environment applications mappings: environment -> response
  2. Hello world sub { my $env = shift; return [

    200, ["Content-Type" => "text/plain"], ["Hello World"], ]; }
  3. $env An unblessed hashref CGI keys without period REQUEST METHOD

    SCRIPT NAME QUERY STRING . . . PSGI-specific keys psgi.version psgi.url scheme psgi.input psgi.errors psgi.multithread psgi.multiprocess psgi.run once psgi.nonblocking psgi.streaming
  4. Middleware package Plack::Middleware::Foo; use parent qw(Plack::Middleware); sub call { my

    ($self, $env) = @_; # pre-process $env my $response = $self->app->($env); # post-process $response return $response; } # or for delayed response Plack::Util::response_cb($response, sub { my $response = shift; ... })
  5. DevTools with Aspect package Plack::Middleware::DevTools; use parent qw(Plack::Middleware); use Aspect

    (); sub call { my ($self, $env) = @_; my @hooks; ... # hooks ... my $response = $self->app->($env); # extract data from $env undef $env; return $response; }
  6. Tracing hook $env->{"devtools.http"} = []; push @hooks, Aspect::before { my

    (undef, $url) = $_->args; push @{$env->{"devtools.http"}}, $url; } Aspect::call qr/^LWP::UserAgent::(?:get|post)$/;
  7. Faking hook push @hooks, Aspect::after { my @args = $_->args;

    my $true_result = $_->return_value; my $fake_result = get_fake_result($true_result, @args); $_->return_value($fake_result); } Aspect::call "API::method" & Aspect::returning;
  8. Find missing translations push @hooks, Aspect::after { if ($cur_lang ne

    $default_lang) { my $msgid = [$_->args]->[0]; my $msgstr = [$_->return_value]->[0]; if ($msgid eq $msgstr) { # replace into db } else { # delete from db } } } Aspect::call qr/::gettext$/;
  9. Dependencies Plack::Builder might have provided information about outer middlewares (but

    it doesn’t) Communication via $env P::M::MyAuth sets $env->{"myauth.user id"} P::M::MyUser fetches user data from DB using $env->{"myauth.user id"} and puts it in $env->{"myuser.user"}

More Decks by Oleg Komarov

Other Decks in Programming