Assume FastCGI mode if STDIN is a socket (works some places env vars fail)
[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;
e27ab5c5 48 require Plack::Server::CGI;
b9e047ef 49 Plack::Server::CGI->run($self->to_psgi_app);
d3a61609 50}
51
e27ab5c5 52sub _run_fcgi {
53 my $self = shift;
54 require Plack::Server::FCGI;
b9e047ef 55 Plack::Server::FCGI->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
81 $self->_run_test_request(@args);
82}
83
84sub _run_test_request {
85 my ($self, $method, $path, @rest) = @_;
86
87 require HTTP::Request;
e27ab5c5 88 require Plack::Test;
913a9cf9 89
4ba6d891 90 my $request = HTTP::Request->new($method => $path);
91 if ($method eq 'POST' or $method eq 'PUT' and @rest) {
92 my $content = do {
93 require URI;
94 my $url = URI->new('http:');
95 $url->query_form(@rest);
96 $url->query;
97 };
98 $request->header('Content-Type' => 'application/x-www-form-urlencoded');
99 $request->header('Content-Length' => length($content));
100 $request->content($content);
101 }
e27ab5c5 102 my $response;
4ba6d891 103 Plack::Test::test_psgi(
104 $self->to_psgi_app, sub { $response = shift->($request) }
105 );
baabba33 106 print STDERR $response->status_line."\n";
107 print STDERR $response->headers_as_string("\n")."\n";
f9d0d382 108 my $content = $response->content;
109 $content .= "\n" if length($content) and $content !~ /\n\z/;
110 print STDOUT $content if $content;
913a9cf9 111}
112
d104fb1d 113sub _run_cli {
114 my $self = shift;
115 die $self->_cli_usage;
116}
117
118sub _cli_usage {
119 "To run this script in CGI test mode, pass a URL path beginning with /:\n".
120 "\n".
121 " $0 /some/path\n".
122 " $0 /\n"
123}
124
5c33dda5 1251;
32d29dcd 126
127=head1 NAME
128
6a4808bf 129Web::Simple::Application - A base class for your Web-Simple application
32d29dcd 130
131=head1 DESCRIPTION
132
133This is a base class for your L<Web::Simple> application. You probably don't
134need to construct this class yourself, since L<Web::Simple> does the 'heavy
135lifting' for you in that regards.
136
137=head1 METHODS
138
6a4808bf 139This class exposes the following public methods.
32d29dcd 140
141=head2 default_config
142
6a4808bf 143Merges with the C<config> initializer to provide configuration information for
144your application. For example:
32d29dcd 145
146 sub default_config {
147 (
148 title => 'Bloggery',
149 posts_dir => $FindBin::Bin.'/posts',
150 );
151 }
152
6a4808bf 153Now, the C<config> attribute of C<$self> will be set to a HashRef
32d29dcd 154containing keys 'title' and 'posts_dir'.
155
12b3e9a3 156The keys from default_config are merged into any config supplied, so
157if you construct your application like:
6a4808bf 158
12b3e9a3 159 MyWebSimpleApp::Web->new(
160 config => { title => 'Spoon', environment => 'dev' }
161 )
6a4808bf 162
12b3e9a3 163then C<config> will contain:
6a4808bf 164
12b3e9a3 165 {
166 title => 'Spoon',
167 posts_dir => '/path/to/myapp/posts',
168 environment => 'dev'
169 }
32d29dcd 170
12b3e9a3 171=head2 run_if_script
32d29dcd 172
12b3e9a3 173The run_if_script method is designed to be used at the end of the script
174or .pm file where your application class is defined - for example:
32d29dcd 175
176 ## my_web_simple_app.pl
177 #!/usr/bin/env perl
178 use Web::Simple 'HelloWorld';
179
180 {
181 package HelloWorld;
182
183 sub dispatch_request {
184 sub (GET) {
185 [ 200, [ 'Content-type', 'text/plain' ], [ 'Hello world!' ] ]
186 },
187 sub () {
188 [ 405, [ 'Content-type', 'text/plain' ], [ 'Method not allowed' ] ]
189 }
190 }
191 }
192
193 HelloWorld->run_if_script;
194
12b3e9a3 195This returns a true value, so your file is now valid as a module - so
6a4808bf 196
12b3e9a3 197 require 'my_web_simple_app.pl';
6a4808bf 198
12b3e9a3 199 my $hw = HelloWorld->new;
6a4808bf 200
12b3e9a3 201will work fine (and you can rename it to lib/HelloWorld.pm later to make it
202a real use-able module).
6a4808bf 203
12b3e9a3 204However, it detects if it's being run as a script (via testing $0) and if
205so attempts to do the right thing.
32d29dcd 206
12b3e9a3 207If run under a CGI environment, your application will execute as a CGI.
32d29dcd 208
12b3e9a3 209If run under a FastCGI environment, your application will execute as a
210FastCGI process (this works both for dynamic shared-hosting-style FastCGI
211and for apache FastCgiServer style setups).
32d29dcd 212
12b3e9a3 213If run from the commandline with a URL path, it runs a GET request against
214that path -
32d29dcd 215
12b3e9a3 216 $ perl -Ilib examples/hello-world/hello-world.cgi /
217 200 OK
218 Content-Type: text/plain
219
220 Hello world!
32d29dcd 221
12b3e9a3 222Additionally, you can treat the file as though it were a standard PSGI
223application file (*.psgi). For example you can start up up with C<plackup>
224
225 plackup my_web_simple_app.pl
32d29dcd 226
12b3e9a3 227or C<starman>
32d29dcd 228
12b3e9a3 229 starman my_web_simple_app.pl
230
231=head2 to_psgi_app
232
233This method is called by L</run_if_script> to create the L<PSGI> app coderef
234for use via L<Plack> and L<plackup>. If you want to globally add middleware,
235you can override this method:
6a4808bf 236
237 use Web::Simple 'HelloWorld';
238 use Plack::Builder;
239
240 {
241 package HelloWorld;
242
243
244 around 'to_psgi_app', sub {
245 my ($orig, $self) = (shift, shift);
246 my $app = $self->$orig(@_);
247 builder {
248 enable ...; ## whatever middleware you want
249 $app;
250 };
251 };
252 }
253
12b3e9a3 254This method can also be used to mount a Web::Simple application within
255a separate C<*.psgi> file -
256
257 use strictures 1;
258 use Plack::Builder;
259 use WSApp;
260 use AnotherWSApp;
261
262 builder {
263 mount '/' => WSApp->to_psgi_app;
264 mount '/another' => AnotherWSApp->to_psgi_app;
265 };
266
267This method can be called as a class method, in which case it implicitly
268calls ->new, or as an object method ... in which case it doesn't.
32d29dcd 269
270=head2 run
271
272Used for running your application under stand-alone CGI and FCGI modes. Also
273useful for testing:
274
275 my $app = MyWebSimpleApp::Web->new;
276 my $c = HTTP::Request::AsCGI->new(@args)->setup;
277 $app->run;
278
7e103e8e 279=head1 AUTHORS
32d29dcd 280
7e103e8e 281See L<Web::Simple> for authors.
32d29dcd 282
7e103e8e 283=head1 COPYRIGHT AND LICENSE
32d29dcd 284
7e103e8e 285See L<Web::Simple> for the copyright and license.
32d29dcd 286
287=cut