How do you use Plack :: Middleware :: Session with a Twiggy server?

I have a TwiggyPerl based server:

my $app = sub { my $req = Plack::Request->new(shift); ... };
my $twiggy = Twiggy::Server->new(port => $port);
$twiggy->register_service($app);

It works fine, but now I want to add session management to it (to handle user authentication). I see that CPAN has a module Plack::Middleware::Session, but based on the documents for it and Twiggy, I don’t know how to use the two together. I have reason to believe that this is possible because in my $ application I am dealing with Plack materials.

Alternatively for use Plack::Middleware::Session, is there another way that I can easily get and set cookie values ​​and maintain session state for authentication purposes? (Each page load requested by the user is processed in a new server fork.)

+4
source share
2 answers

You can just tie it together. builderfunct from Plack :: Builder will port your application to Middleware (or several). Then you just transfer it as a new Twiggy app.

use Plack::Builder;
use Twiggy::Server;

my $app = sub {
    my $env = shift;
    my $req = Plack::Request->new($env);
    my $session = $env->{'psgix.session'};
    return [
        200,
        [ 'Content-Type' => 'text/plain' ],
        [ "Hello, you've been here for ", $session->{counter}++, "th time!" ],
    ];
};

$app = builder {
    enable 'Session', store => 'File';
    $app;
};

my $twiggy = Twiggy::Server->new(port => 3000);
$twiggy->register_service($app);

AE::cv->recv;

Please note that the buildernew application will return, but it will not end in $appunless you have assigned it. You can also just put builderin register_serviceas follows:

my $twiggy = Twiggy::Server->new(port => 3000);
$twiggy->register_service(builder {
    enable 'Session', store => 'File';
    $app;
});

Or, of course, you could get rid of Twiggy :: Server and run the command line tool twiggyor plackupfrom Twiggy.

+4
source

The joy of PSGI is that everything connects the same every time.

PSGI , build, Plack:: Builder.

, , - :

use Twiggy::Server;
use Plack::Builder;
use Plack::Middleware::Session;

my $app = sub { my $req = Plack::Request->new(shift); ... };

$app = builder {
  enable 'Session';
  $app;
}

my $twiggy = Twiggy::Server->new(port => $port);
$twiggy->register_service($app);
+1

All Articles