document and changelog run_test_request
[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   Web::Dispatch->new(
29     app => sub { $self->dispatch_request(@_), $final },
30     node_class => 'Web::Simple::DispatchNode',
31     node_args => { app_object => $self }
32   );
33 }
34
35 sub _build_final_dispatcher {
36   [ 404, [ 'Content-type', 'text/plain' ], [ 'Not found' ] ]
37 }
38
39 sub run_if_script {
40   # ->to_psgi_app is true for require() but also works for plackup
41   return $_[0]->to_psgi_app if caller(1);
42   my $self = ref($_[0]) ? $_[0] : $_[0]->new;
43   $self->run(@_);
44 }
45
46 sub _run_cgi {
47   my $self = shift;
48   require Plack::Handler::CGI;
49   Plack::Handler::CGI->new->run($self->to_psgi_app);
50 }
51
52 sub _run_fcgi {
53   my $self = shift;
54   require Plack::Handler::FCGI;
55   Plack::Handler::FCGI->new->run($self->to_psgi_app);
56 }
57
58 sub to_psgi_app {
59   my $self = ref($_[0]) ? $_[0] : $_[0]->new;
60   $self->_dispatcher->to_app;
61 }
62
63 sub run {
64   my $self = shift;
65   if (
66     $ENV{PHP_FCGI_CHILDREN} || $ENV{FCGI_ROLE} || $ENV{FCGI_SOCKET_PATH}
67     || -S STDIN # STDIN is a socket, almost certainly FastCGI
68     ) {
69     return $self->_run_fcgi;
70   } elsif ($ENV{GATEWAY_INTERFACE}) {
71     return $self->_run_cgi;
72   }
73   unless (@ARGV && $ARGV[0] =~ m{^[A-Z/]}) {
74     return $self->_run_cli(@ARGV);
75   }
76
77   my @args = @ARGV;
78
79   unshift(@args, 'GET') if $args[0] =~ m{^/};
80
81   $self->_run_cli_test_request(@args);
82 }
83
84 sub _test_request_spec_to_http_request {
85   my ($self, $method, $path, @rest) = @_;
86
87   # if it's a reference, assume a request object
88   return $method if ref($method);
89
90   my $request = HTTP::Request->new($method => $path);
91
92   if (($method eq 'POST' or $method eq 'PUT') and @rest) {
93     my $content = do {
94       require URI;
95       my $url = URI->new('http:');
96       $url->query_form(@rest);
97       $url->query;
98     };
99     $request->header('Content-Type' => 'application/x-www-form-urlencoded');
100     $request->header('Content-Length' => length($content));
101     $request->content($content);
102   }
103
104   return $request;
105 }
106
107 sub run_test_request {
108   my ($self, @req) = @_;
109
110   require HTTP::Request;
111   require Plack::Test;
112
113   my $request = $self->_test_request_spec_to_http_request(@req);
114
115   Plack::Test::test_psgi(
116     $self->to_psgi_app, sub { shift->($request) }
117   );
118 }
119
120 sub _run_cli_test_request {
121   my ($self, @req) = @_;
122   my $response = $self->run_test_request(@req);
123
124   binmode(STDOUT); binmode(STDERR); # for win32
125
126   print STDERR $response->status_line."\n";
127   print STDERR $response->headers_as_string("\n")."\n";
128   my $content = $response->content;
129   $content .= "\n" if length($content) and $content !~ /\n\z/;
130   print STDOUT $content if $content;
131 }
132
133 sub _run_cli {
134   my $self = shift;
135   die $self->_cli_usage;
136 }
137
138 sub _cli_usage {
139   "To run this script in CGI test mode, pass a URL path beginning with /:\n".
140   "\n".
141   "  $0 /some/path\n".
142   "  $0 /\n"
143 }
144
145 1;
146
147 =head1 NAME
148
149 Web::Simple::Application - A base class for your Web-Simple application
150
151 =head1 DESCRIPTION
152
153 This is a base class for your L<Web::Simple> application.  You probably don't
154 need to construct this class yourself, since L<Web::Simple> does the 'heavy
155 lifting' for you in that regards.
156
157 =head1 METHODS
158
159 This class exposes the following public methods.
160
161 =head2 default_config
162
163 Merges with the C<config> initializer to provide configuration information for
164 your application.  For example:
165
166   sub default_config {
167     (
168       title => 'Bloggery',
169       posts_dir => $FindBin::Bin.'/posts',
170     );
171   }
172
173 Now, the C<config> attribute of C<$self>  will be set to a HashRef
174 containing keys 'title' and 'posts_dir'.
175
176 The keys from default_config are merged into any config supplied, so
177 if you construct your application like:
178
179   MyWebSimpleApp::Web->new(
180     config => { title => 'Spoon', environment => 'dev' }
181   )
182
183 then C<config> will contain:
184
185   {
186     title => 'Spoon',
187     posts_dir => '/path/to/myapp/posts',
188     environment => 'dev'
189   }
190
191 =head2 run_if_script
192
193 The run_if_script method is designed to be used at the end of the script
194 or .pm file where your application class is defined - for example:
195
196   ## my_web_simple_app.pl
197   #!/usr/bin/env perl
198   use Web::Simple 'HelloWorld';
199
200   {
201     package HelloWorld;
202
203     sub dispatch_request {
204       sub (GET) {
205         [ 200, [ 'Content-type', 'text/plain' ], [ 'Hello world!' ] ]
206       },
207       sub () {
208         [ 405, [ 'Content-type', 'text/plain' ], [ 'Method not allowed' ] ]
209       }
210     }
211   }
212
213   HelloWorld->run_if_script;
214
215 This returns a true value, so your file is now valid as a module - so
216
217   require 'my_web_simple_app.pl';
218
219   my $hw = HelloWorld->new;
220
221 will work fine (and you can rename it to lib/HelloWorld.pm later to make it
222 a real use-able module).
223
224 However, it detects if it's being run as a script (via testing $0) and if
225 so attempts to do the right thing.
226
227 If run under a CGI environment, your application will execute as a CGI.
228
229 If run under a FastCGI environment, your application will execute as a
230 FastCGI process (this works both for dynamic shared-hosting-style FastCGI
231 and for apache FastCgiServer style setups).
232
233 If run from the commandline with a URL path, it runs a GET request against
234 that path -
235
236   $ perl -Ilib examples/hello-world/hello-world.cgi /
237   200 OK
238   Content-Type: text/plain
239   
240   Hello world!
241
242 Additionally, you can treat the file as though it were a standard PSGI
243 application file (*.psgi).  For example you can start up up with C<plackup>
244
245   plackup my_web_simple_app.pl
246
247 or C<starman>
248
249   starman my_web_simple_app.pl
250
251 =head2 to_psgi_app
252
253 This method is called by L</run_if_script> to create the L<PSGI> app coderef
254 for use via L<Plack> and L<plackup>. If you want to globally add middleware,
255 you can override this method:
256
257   use Web::Simple 'HelloWorld';
258   use Plack::Builder;
259  
260   {
261     package HelloWorld;
262
263   
264     around 'to_psgi_app', sub {
265       my ($orig, $self) = (shift, shift);
266       my $app = $self->$orig(@_); 
267       builder {
268         enable ...; ## whatever middleware you want
269         $app;
270       };
271     };
272   }
273
274 This method can also be used to mount a Web::Simple application within
275 a separate C<*.psgi> file -
276
277   use strictures 1;
278   use Plack::Builder;
279   use WSApp;
280   use AnotherWSApp;
281
282   builder {
283     mount '/' => WSApp->to_psgi_app;
284     mount '/another' => AnotherWSApp->to_psgi_app;
285   };
286
287 This method can be called as a class method, in which case it implicitly
288 calls ->new, or as an object method ... in which case it doesn't.
289
290 =head2 run
291
292 Used for running your application under stand-alone CGI and FCGI modes.
293
294 I should document this more extensively but run_if_script will call it when
295 you need it, so don't worry about it too much.
296
297 =head2 run_test_request
298
299   my $res = $app->run_test_request(GET => '/');
300
301   my $res = $app->run_test_request(POST => '/' => %form);
302
303   my $res = $app->run_test_request($http_request);
304
305 Accepts either an L<HTTP::Request> object or ($method, $path) and runs that
306 request against the application, returning an L<HTTP::Response> object.
307
308 If the HTTP method is POST or PUT, then a series of pairs can be passed after
309 this to create a form style message body. If you need to test an upload, then
310 create an L<HTTP::Request> object by hand or use the C<POST> subroutine
311 provided by L<HTTP::Request::Common>.
312
313 =head1 AUTHORS
314
315 See L<Web::Simple> for authors.
316
317 =head1 COPYRIGHT AND LICENSE
318
319 See L<Web::Simple> for the copyright and license.
320
321 =cut