/
PSGI.pm
107 lines (79 loc) · 2.12 KB
/
PSGI.pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package Squatting::On::PSGI;
use strict;
use 5.008_001;
our $VERSION = '0.06';
use CGI::Cookie;
use Plack::Request;
use Squatting::H;
# p for private
my %p;
$p{init_cc} = sub {
my ($c, $env) = @_;
my $cc = $c->clone;
$cc->env = $env;
$cc->cookies = $p{c}->($env->{HTTP_COOKIE} || '');
$cc->input = $p{i}->($env);
$cc->headers = { 'Content-Type' => 'text/html' };
$cc->v = { };
$cc->state = $env->{'psgix.session'};
$cc->status = 200;
$cc;
};
# \%input = i($env) # Extract CGI parameters from an env object
$p{i} = sub {
my $r = Plack::Request->new($_[0]);
$r->parameters->as_hashref_mixed;
};
# \%cookies = $p{c}->($cookie_header) # Parse Cookie header(s).
$p{c} = sub {
+{ map { ref($_) ? $_->value : $_ } CGI::Cookie->parse($_[0]) };
};
sub psgi {
my ($app, $env) = @_;
$env->{PATH_INFO} ||= "/";
$env->{REQUEST_PATH} ||= do {
my $script_name = $env->{SCRIPT_NAME};
$script_name =~ s{/$}{};
$script_name . $env->{PATH_INFO};
};
$env->{REQUEST_URI} ||= do {
($env->{QUERY_STRING})
? "$env->{REQUEST_PATH}?$env->{QUERY_STRING}"
: $env->{REQUEST_PATH};
};
my $res;
eval {
no strict 'refs';
my ($c, $args) = &{ $app . "::D" }($env->{REQUEST_PATH});
my $cc = $p{init_cc}->($c, $env);
my $content = $app->service($cc, @$args);
$res = [ $cc->status, [ %{ $cc->{headers} } ], [$content], ];
};
if ($@) {
$res = [ 500, [ 'Content-Type' => 'text/plain' ], ["<pre>$@</pre>"] ];
}
return $res;
}
1;
__END__
=head1 NAME
Squatting::On::PSGI - Run Squatting app on PSGI
=head1 SYNOPSIS
# app.psgi
use App 'On::PSGI';
App->init;
my $handler = sub {
my $env = shift;
App->psgi($env);
};
=head1 DESCRIPTION
Squatting::On::PSGI is an adapter to run Squatting apps on PSGI implementations.
=head1 AUTHOR
Tatsuhiko Miyagawa E<lt>miyagawa@bulknews.netE<gt> (original author)
John Beppu E<lt>beppu@cpan.orgE<gt> (current maintainer)
=head1 LICENSE
This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself.
=head1 SEE ALSO
L<Squatting::On::CGI> L<CGI::PSGI>
=cut