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