Skip to content

Instantly share code, notes, and snippets.

@djacobs
Created March 1, 2011 03:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save djacobs/848569 to your computer and use it in GitHub Desktop.
Save djacobs/848569 to your computer and use it in GitHub Desktop.
Newbie plack mistake
# shebang
use constant USER => 'xxxx';
use constant PASS => 'xxxx';
# libraries
use CGI::PSGI;
use Data::Dumper;
use File::Glob qw(:globally :nocase);
use JSON;
use MongoDB;
use Plack::App::URLMap;
# globals or reused
my ( $key, $value );
my $now = time;
my $setid = join( '.', $now, SERVER, int( rand() * 100000 ) );
my $connection =
MongoDB::Connection->new( host => 'dbh01.mongolab.com', port => 27017 );
$connection->authenticate( 'blog1', 'USER', 'PASS' );
my $database = $connection->blog1;
# Not sure exactly what this does!
# Try http://advent.plackperl.org/2009/12/day-16-adding-jsonp-support-to-your-app.html
#use Plack::Builder;
#builder {
# enable "JSONP";
# $app;
#};
# My usual
#sub debug {
# DEBUG and print "DEBUG: @_\n";
# DEBUG_SAVE and print STDERR @_, "\n";
#}
# Write JSON
my $app1 = sub {
my $env = shift;
my $q = CGI::PSGI->new($env);
my $collection = $database->post;
# debug(Dumper($q->param));
# post forms here
# return redirect
# return JSON
my $body = JSON::encode_json( { hello => 'world', } );
return [ 200, [ 'Content-Type', 'application/json' ], [$body] ];
};
# Read JSON
my $app2 = sub {
my $env = shift;
my $q = CGI::PSGI->new($env);
my $collection = $database->post;
# check params here
# return JSON
my $body = JSON::encode_json( { hello => 'world', } );
return [ 200, [ 'Content-Type', 'application/json' ], [$body] ];
};
my $app3 = sub {
my $env = shift;
my $q = CGI::PSGI->new($env);
my $collection = $database->user;
};
my $app4 = sub {
my $env = shift;
my $q = CGI::PSGI->new($env);
my $collection = $database->stat;
};
my $app = Plack::App::URLMap->new;
$app->mount( "/write" => $app1 );
$app->mount( "/read" => $app2 );
$app->mount( "/user" => $app3 );
$app->mount( "/stat" => $app4 );
@djacobs
Copy link
Author

djacobs commented Mar 1, 2011

I forgot app->to_app at the end.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment