#!perl # MOJO_MODE=production hypnotoad myapp.pl use strict; use warnings; use Mojolicious::Lite; use Mojo::Log; # if you enable this then you need to set # render handler to 'tx', like this: # $c->render( ... 'handler' => 'tx' ...) #plugin 'xslate_renderer'; my $PORT = '3000'; my $COOKIENAME = 'cook'; my $log = Mojo::Log->new(); # make sure you set the secret because it defaults to the app's name!!! # cookie name and secret must be different for different apps. app->secrets(['ajhgdauyda']); # secure cookies are those sent over HTTPS only # so if part of the app is over HTTP, the cookie will not be sent! app->log->level('info'); app->sessions->secure(1); app->sessions->cookie_name($COOKIENAME); $log->info("session cookie is '$COOKIENAME'."); # this is important if nginx is rewriting the url (e.g. handling multiple sites # it removes part of the url but we know the original and we must append it # on each request we make app->hook( before_dispatch => sub { my $c = shift; if ( my $base = $c->req->headers->header('X-Request-Base') ) { $log->info("found base '$base' and setting it ..."); my $u = Mojo::URL->new($base); $c->req->url->base($u); # this will go to the templates $c->stash('RequestBaseHeader' => Mojo::URL->new($u->to_abs)); } else { $c->stash('RequestBaseHeader' => ''); } } ); ############################################################ # end of startup, start the routes ############################################################ get '/' => sub { my $c = $_[0]; if( exists($c->session->{'u'}) && defined($c->session->{'u'}) ){ # we have a session, read it and send it to the template # to print some content. $log->info("session found and sent to template ..."); $c->stash( 'd' => $c->session->{'u'} ); } else { # there is no session, set it $log->info("setting the session ..."); $c->session->{'u'} = {'hello' => 'hello i am session content'}; $c->stash( 'd' => undef ); } $c->render( 'template' => 'checksession', # down in __DATA__ 'format' => 'html', 'handler' => 'ep', ); }; my $daemon = Mojo::Server::Daemon->new( app => app, listen => ["http://*:${PORT}"] ); $log->info("$0 : started listening on port ${PORT} and with mode ". app->mode ." ..."); $daemon->run; #app->start; __DATA__ @@ checksession.html.tx
: if( $d == nil){
No session yet, hopefully it has been set now!
Reload the page to see if it has been set. : } else {
You have session with this content: : for $d.keys() -> $k { '<: $k :>' => '<: $d[$k] :>' : } : } @@ checksession.html.ep
% if( defined $d ){You have session with this content: % for my $k (keys %$d){ key='<%= $k =%>' = '<%= $d->{$k} =%>' % } % } else {
No session yet, hopefully it was set!
Reload the page to see if it has been set. % }