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