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