Handwritten Router
file: code/HandwrittenPSGIRouter
1: package MyApp::PSGI;
2: use 5.018;
3: use strict;
4: use warnings;
5: use Try::Tiny;
6: use Plack::Request;
7:
8: my %poor_persons_routes = (
9: '/foo' => \&foo,
10: '/bar' => \&bar,
11: );
12:
13: sub run_psgi {
14: my $self = shift;
15:
16: my $app = sub {
17: my $env = shift;
18: my $req = Plack::Request->new($env);
19:
20: my $path = $req->path_info;
21:
22: try {
23: my $action = $poor_persons_routes{$path};
24: if ($action) {
25: my $res = $action->($req);
26: return $res->finalize;
27: }
28: else {
29: return Plack::Response->new(404)->finalize;
30: }
31: }
32: catch {
33: my $e = $_;
34:
35: if ( ref($e) eq 'Plack::Response' ) {
36: return $e->finalize;
37: }
38: else {
39: return Plack::Response->new( 500, undef, "$_" )->finalize;
40: }
41: };
42: };
43: return $app;
44: }
45:
46: sub foo {
47: my $req = shift;
48: return $req->new_response(
49: 200,
50: [ 'Content-Type', 'application/json;charset=utf-8' ],
51: encode_json( { foo => 1 } )
52: );
53: }
54:
55: 1;