fixed CGI detection under mod_cgid
[catagits/Web-Simple.git] / lib / Web / Simple / Application.pm
1 package Web::Simple::Application;
2
3 use Scalar::Util 'weaken';
4
5 use Moo;
6
7 has 'config' => (
8   is => 'ro',
9   default => sub {
10     my ($self) = @_;
11     +{ $self->default_config }
12   },
13   trigger => sub {
14     my ($self, $value) = @_;
15     my %default = $self->default_config;
16     my @not = grep !exists $value->{$_}, keys %default;
17     @{$value}{@not} = @default{@not};
18   }
19 );
20
21 sub default_config { () }
22
23 has '_dispatcher' => (is => 'lazy');
24
25 sub _build__dispatcher {
26   my $self = shift;
27   require Web::Dispatch;
28   require Web::Simple::DispatchNode;
29   my $final = $self->_build_final_dispatcher;
30
31   # We need to weaken both the copy of $self that the
32   # app parameter will close over and the copy that'll
33   # be passed through as a node argument.
34   #
35   # To ensure that this doesn't then result in us being
36   # DESTROYed unexpectedly early, our to_psgi_app method
37   # closes back over $self
38
39   weaken($self);
40   my $node_args = { app_object => $self };
41   weaken($node_args->{app_object});
42   Web::Dispatch->new(
43     app => sub { $self->dispatch_request(@_), $final },
44     node_class => 'Web::Simple::DispatchNode',
45     node_args => $node_args
46   );
47 }
48
49 sub _build_final_dispatcher {
50   [ 404, [ 'Content-type', 'text/plain' ], [ 'Not found' ] ]
51 }
52
53 sub run_if_script {
54   # ->to_psgi_app is true for require() but also works for plackup
55   return $_[0]->to_psgi_app if caller(1);
56   my $self = ref($_[0]) ? $_[0] : $_[0]->new;
57   $self->run(@_);
58 }
59
60 sub _run_cgi {
61   my $self = shift;
62   require Plack::Handler::CGI;
63   Plack::Handler::CGI->new->run($self->to_psgi_app);
64 }
65
66 sub _run_fcgi {
67   my $self = shift;
68   require Plack::Handler::FCGI;
69   Plack::Handler::FCGI->new->run($self->to_psgi_app);
70 }
71
72 sub to_psgi_app {
73   my $self = ref($_[0]) ? $_[0] : $_[0]->new;
74   my $app = $self->_dispatcher->to_app;
75
76   # Close over $self to keep $self alive even though
77   # we weakened the copies the dispatcher has; the
78   # if 0 causes the ops to be optimised away to
79   # minimise the performance impact and avoid void
80   # context warnings while still doing the closing
81   # over part. As Mithaldu said: "Gnarly." ...
82
83   return sub { $self if 0; goto &$app; };
84 }
85
86 sub run {
87   my $self = shift;
88   if (
89     $ENV{PHP_FCGI_CHILDREN} || $ENV{FCGI_ROLE} || $ENV{FCGI_SOCKET_PATH}
90     || ( -S STDIN && !$ENV{GATEWAY_INTERFACE} )
91     # If STDIN is a socket, almost certainly FastCGI, except for mod_cgid
92     ) {
93     return $self->_run_fcgi;
94   } elsif ($ENV{GATEWAY_INTERFACE}) {
95     return $self->_run_cgi;
96   }
97   unless (@ARGV && $ARGV[0] =~ m{^[A-Z/]}) {
98     return $self->_run_cli(@ARGV);
99   }
100
101   my @args = @ARGV;
102
103   unshift(@args, 'GET') if $args[0] =~ m{^/};
104
105   $self->_run_cli_test_request(@args);
106 }
107
108 sub _test_request_spec_to_http_request {
109   my ($self, $method, $path, @rest) = @_;
110
111   # if it's a reference, assume a request object
112   return $method if ref($method);
113
114   my $request = HTTP::Request->new($method => $path);
115
116   my @params;
117
118   while (my ($header, $value) = splice(@rest, 0, 2)) {
119     unless ($header =~ s/:$//) {
120       push @params, $header, $value;
121     }
122     $header =~ s/_/-/g;
123     if ($header eq 'Content') {
124       $request->content($value);
125     } else {
126       $request->headers->push_header($header, $value);
127     }
128   }
129
130   if (($method eq 'POST' or $method eq 'PUT') and @params) {
131     my $content = do {
132       require URI;
133       my $url = URI->new('http:');
134       $url->query_form(@params);
135       $url->query;
136     };
137     $request->header('Content-Type' => 'application/x-www-form-urlencoded');
138     $request->header('Content-Length' => length($content));
139     $request->content($content);
140   }
141
142   return $request;
143 }
144
145 sub run_test_request {
146   my ($self, @req) = @_;
147
148   require HTTP::Request;
149   require Plack::Test;
150
151   my $request = $self->_test_request_spec_to_http_request(@req);
152
153   Plack::Test::test_psgi(
154     $self->to_psgi_app, sub { shift->($request) }
155   );
156 }
157
158 sub _run_cli_test_request {
159   my ($self, @req) = @_;
160   my $response = $self->run_test_request(@req);
161
162   binmode(STDOUT); binmode(STDERR); # for win32
163
164   print STDERR $response->status_line."\n";
165   print STDERR $response->headers_as_string("\n")."\n";
166   my $content = $response->content;
167   $content .= "\n" if length($content) and $content !~ /\n\z/;
168   print STDOUT $content if $content;
169 }
170
171 sub _run_cli {
172   my $self = shift;
173   die $self->_cli_usage;
174 }
175
176 sub _cli_usage {
177   "To run this script in CGI test mode, pass a URL path beginning with /:\n".
178   "\n".
179   "  $0 /some/path\n".
180   "  $0 /\n"
181 }
182
183 1;
184
185 =head1 NAME
186
187 Web::Simple::Application - A base class for your Web-Simple application
188
189 =head1 DESCRIPTION
190
191 This is a base class for your L<Web::Simple> application.  You probably don't
192 need to construct this class yourself, since L<Web::Simple> does the 'heavy
193 lifting' for you in that regards.
194
195 =head1 METHODS
196
197 This class exposes the following public methods.
198
199 =head2 default_config
200
201 Merges with the C<config> initializer to provide configuration information for
202 your application.  For example:
203
204   sub default_config {
205     (
206       title => 'Bloggery',
207       posts_dir => $FindBin::Bin.'/posts',
208     );
209   }
210
211 Now, the C<config> attribute of C<$self>  will be set to a HashRef
212 containing keys 'title' and 'posts_dir'.
213
214 The keys from default_config are merged into any config supplied, so
215 if you construct your application like:
216
217   MyWebSimpleApp::Web->new(
218     config => { title => 'Spoon', environment => 'dev' }
219   )
220
221 then C<config> will contain:
222
223   {
224     title => 'Spoon',
225     posts_dir => '/path/to/myapp/posts',
226     environment => 'dev'
227   }
228
229 =head2 run_if_script
230
231 The run_if_script method is designed to be used at the end of the script
232 or .pm file where your application class is defined - for example:
233
234   ## my_web_simple_app.pl
235   #!/usr/bin/env perl
236   use Web::Simple 'HelloWorld';
237
238   {
239     package HelloWorld;
240
241     sub dispatch_request {
242       sub (GET) {
243         [ 200, [ 'Content-type', 'text/plain' ], [ 'Hello world!' ] ]
244       },
245       sub () {
246         [ 405, [ 'Content-type', 'text/plain' ], [ 'Method not allowed' ] ]
247       }
248     }
249   }
250
251   HelloWorld->run_if_script;
252
253 This returns a true value, so your file is now valid as a module - so
254
255   require 'my_web_simple_app.pl';
256
257   my $hw = HelloWorld->new;
258
259 will work fine (and you can rename it to lib/HelloWorld.pm later to make it
260 a real use-able module).
261
262 However, it detects if it's being run as a script (via testing $0) and if
263 so attempts to do the right thing.
264
265 If run under a CGI environment, your application will execute as a CGI.
266
267 If run under a FastCGI environment, your application will execute as a
268 FastCGI process (this works both for dynamic shared-hosting-style FastCGI
269 and for apache FastCgiServer style setups).
270
271 If run from the commandline with a URL path, it runs a GET request against
272 that path -
273
274   $ perl -Ilib examples/hello-world/hello-world.cgi /
275   200 OK
276   Content-Type: text/plain
277   
278   Hello world!
279
280 You can also provide a method name -
281
282   $ perl -Ilib examples/hello-world/hello-world.cgi POST /
283   405 Method Not Allowed
284   Content-Type: text/plain
285   
286   Method not allowed
287
288 For a POST or PUT request, pairs on the command line will be treated
289 as form variables. For any request, pairs on the command line ending in :
290 are treated as headers, and 'Content:' will set the request body -
291
292   $ ./myapp POST / Accept: text/html form_field_name form_field_value
293   
294   $ ./myapp POST / Content-Type: text/json Content: '{ "json": "here" }'
295
296 The body of the response is sent to STDOUT and the headers to STDERR, so
297
298   $ ./myapp GET / >index.html
299
300 will generally do the right thing.
301
302 Additionally, you can treat the file as though it were a standard PSGI
303 application file (*.psgi).  For example you can start up up with C<plackup>
304
305   plackup my_web_simple_app.pl
306
307 or C<starman>
308
309   starman my_web_simple_app.pl
310
311 =head2 to_psgi_app
312
313 This method is called by L</run_if_script> to create the L<PSGI> app coderef
314 for use via L<Plack> and L<plackup>. If you want to globally add middleware,
315 you can override this method:
316
317   use Web::Simple 'HelloWorld';
318   use Plack::Builder;
319  
320   {
321     package HelloWorld;
322
323   
324     around 'to_psgi_app', sub {
325       my ($orig, $self) = (shift, shift);
326       my $app = $self->$orig(@_); 
327       builder {
328         enable ...; ## whatever middleware you want
329         $app;
330       };
331     };
332   }
333
334 This method can also be used to mount a Web::Simple application within
335 a separate C<*.psgi> file -
336
337   use strictures 1;
338   use Plack::Builder;
339   use WSApp;
340   use AnotherWSApp;
341
342   builder {
343     mount '/' => WSApp->to_psgi_app;
344     mount '/another' => AnotherWSApp->to_psgi_app;
345   };
346
347 This method can be called as a class method, in which case it implicitly
348 calls ->new, or as an object method ... in which case it doesn't.
349
350 =head2 run
351
352 Used for running your application under stand-alone CGI and FCGI modes.
353
354 I should document this more extensively but run_if_script will call it when
355 you need it, so don't worry about it too much.
356
357 =head2 run_test_request
358
359   my $res = $app->run_test_request(GET => '/' => %headers);
360
361   my $res = $app->run_test_request(POST => '/' => %headers_or_form);
362
363   my $res = $app->run_test_request($http_request);
364
365 Accepts either an L<HTTP::Request> object or ($method, $path) and runs that
366 request against the application, returning an L<HTTP::Response> object.
367
368 If the HTTP method is POST or PUT, then a series of pairs can be passed after
369 this to create a form style message body. If you need to test an upload, then
370 create an L<HTTP::Request> object by hand or use the C<POST> subroutine
371 provided by L<HTTP::Request::Common>.
372
373 If pairs are passed where the key ends in :, it is instead treated as a
374 headers, so:
375
376   my $res = $app->run_test_request(
377               POST => '/',
378              'Accept:' => 'text/html',
379               some_form_key => 'value'
380             );
381
382 will do what you expect. You can also pass a special key of Content: to
383 set the request body:
384
385   my $res = $app->run_test_request(
386               POST => '/',
387               'Content-Type:' => 'text/json',
388               'Content:' => '{ "json": "here" }',
389             );
390
391 =head1 AUTHORS
392
393 See L<Web::Simple> for authors.
394
395 =head1 COPYRIGHT AND LICENSE
396
397 See L<Web::Simple> for the copyright and license.
398
399 =cut