Merge pull request #7 from tokuhirom/master
[catagits/Web-Session.git] / examples / counter-raw.psgi
1 #!/usr/bin/perl
2 # Simple counter web application
3
4 # NOTE: This example uses Plack::Request to illustrate how
5 # Plack::Middleware::Session interface ($env->{'psgix.session'}) could
6 # be wrapped and integrated as part of the request API. See Tatsumaki
7 # (integrated via subclassing Plack::Request) and Dancer::Session::PSGI
8 # how to adapt Plack::Middleware::Session to web frameworks' APIs.
9
10 # You're not recommended to write a new web application using this style.
11
12 use strict;
13 use Plack::Session;
14 use Plack::Session::State;
15 use Plack::Session::State::Cookie;
16 use Plack::Session::Store;
17 use Plack::Middleware::Session;
18
19 my $app = Plack::Middleware::Session->wrap(
20     sub {
21         my $env = shift;
22         my $r   = Plack::Request->new( $env );
23
24         return [ 404, [], [] ] if $r->path_info =~ /favicon.ico/;
25
26         my $session = $r->session;
27
28         my $id      = $session->id;
29         my $counter = $session->get('counter') || 0;
30
31         $session->set( 'counter' => $counter + 1 );
32
33         my $resp;
34
35         if ( $r->param( 'logout' ) ) {
36             $session->expire;
37             $resp = $r->new_response;
38             $resp->redirect( $r->path_info );
39         }
40         else {
41             $resp = $r->new_response(
42                 200,
43                 [ 'Content-Type' => 'text/html' ],
44                 [
45                     qq{
46                         <html>
47                         <head>
48                             <title>Plack::Middleware::Session Example</title>
49                         </head>
50                         <body>
51                             <h1>Session Id: ${id}</h1>
52                             <h2>Counter: ${counter}</h2>
53                             <hr/>
54                             <a href="/?logout=1">Logout</a>
55                         </body>
56                         </html>
57                     }
58                 ]
59             );
60         }
61
62         $resp->finalize;
63     },
64     state => Plack::Session::State::Cookie->new,
65     store => Plack::Session::Store->new,
66 );