1 package Web::Simple::Application;
3 use Scalar::Util 'weaken';
12 +{ $self->default_config }
15 my ($self, $value) = @_;
16 my %default = $self->default_config;
17 my @not = grep !exists $value->{$_}, keys %default;
18 @{$value}{@not} = @default{@not};
22 sub default_config { () }
24 has '_dispatcher' => (is => 'lazy');
26 sub _build__dispatcher {
28 require Web::Dispatch;
29 my $final = $self->_build_final_dispatcher;
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.
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
41 dispatch_app => sub { $self->dispatch_request(@_), $final },
42 dispatch_object => $self
44 weaken($dispatch_args{dispatch_object});
45 Web::Dispatch->new(%dispatch_args);
48 sub _build_final_dispatcher {
49 [ 404, [ 'Content-type', 'text/plain' ], [ 'Not found' ] ]
53 my ( $self, @args ) = @_;
54 # ->to_psgi_app is true for require() but also works for plackup
55 return $self->to_psgi_app(@args) if caller(1);
56 $self = ref($self) ? $self : $self->new(@args);
62 require Plack::Handler::CGI;
63 Plack::Handler::CGI->new->run($self->to_psgi_app);
68 require Plack::Handler::FCGI;
69 Plack::Handler::FCGI->new->run($self->to_psgi_app);
73 my ($invocant, @args) = @_;
75 unless (ref($invocant)) {
79 try { $invocant->new(@args)->to_psgi_app }
80 catch { die "Failed to auto-create new ${invocant} object for to_psgi_app: $_"; }
87 my $app = $self->_dispatcher->to_app;
89 # Close over $self to keep $self alive even though
90 # we weakened the copies the dispatcher has; the
91 # if 0 causes the ops to be optimised away to
92 # minimise the performance impact and avoid void
93 # context warnings while still doing the closing
94 # over part. As Mithaldu said: "Gnarly." ...
96 return sub { $self if 0; goto &$app; };
102 $ENV{PHP_FCGI_CHILDREN} || $ENV{FCGI_ROLE} || $ENV{FCGI_SOCKET_PATH}
103 || ( -S STDIN && !$ENV{GATEWAY_INTERFACE} )
104 # If STDIN is a socket, almost certainly FastCGI, except for mod_cgid
106 return $self->_run_fcgi;
107 } elsif ($ENV{GATEWAY_INTERFACE}) {
108 return $self->_run_cgi;
110 unless (@ARGV && $ARGV[0] =~ m{(^[A-Z/])|\@}) {
111 return $self->_run_cli(@ARGV);
116 unshift(@args, 'GET') if $args[0] !~ /^[A-Z]/;
118 $self->_run_cli_test_request(@args);
121 sub _test_request_spec_to_http_request {
122 my ($self, $method, $path, @rest) = @_;
124 # if it's a reference, assume a request object
125 return $method if ref($method);
127 if ($path =~ s/^(.*?)\@//) {
129 require MIME::Base64;
130 unshift @rest, 'Authorization:', 'Basic '.MIME::Base64::encode($basic);
133 my $request = HTTP::Request->new($method => $path);
137 while (my ($header, $value) = splice(@rest, 0, 2)) {
138 unless ($header =~ s/:$//) {
139 push @params, $header, $value;
142 if ($header eq 'Content') {
143 $request->content($value);
145 $request->headers->push_header($header, $value);
149 if (($method eq 'POST' or $method eq 'PUT') and @params) {
152 my $url = URI->new('http:');
153 $url->query_form(@params);
156 $request->header('Content-Type' => 'application/x-www-form-urlencoded');
157 $request->header('Content-Length' => length($content));
158 $request->content($content);
164 sub run_test_request {
165 my ($self, @req) = @_;
167 require HTTP::Request;
171 my $request = $self->_test_request_spec_to_http_request(@req);
173 Plack::Test::test_psgi(
174 $self->to_psgi_app, sub { shift->($request) }
178 sub _run_cli_test_request {
179 my ($self, @req) = @_;
180 my $response = $self->run_test_request(@req);
182 binmode(STDOUT); binmode(STDERR); # for win32
184 print STDERR $response->status_line."\n";
185 print STDERR $response->headers_as_string("\n")."\n";
186 my $content = $response->content;
187 $content .= "\n" if length($content) and $content !~ /\n\z/;
188 print STDOUT $content if $content;
193 die $self->_cli_usage;
197 "To run this script in CGI test mode, pass a URL path beginning with /:\n".
207 Web::Simple::Application - A base class for your Web-Simple application
211 This is a base class for your L<Web::Simple> application. You probably don't
212 need to construct this class yourself, since L<Web::Simple> does the 'heavy
213 lifting' for you in that regards.
217 This class exposes the following public methods.
219 =head2 default_config
221 Merges with the C<config> initializer to provide configuration information for
222 your application. For example:
227 posts_dir => $FindBin::Bin.'/posts',
231 Now, the C<config> attribute of C<$self> will be set to a HashRef
232 containing keys 'title' and 'posts_dir'.
234 The keys from default_config are merged into any config supplied, so
235 if you construct your application like:
237 MyWebSimpleApp::Web->new(
238 config => { title => 'Spoon', environment => 'dev' }
241 then C<config> will contain:
245 posts_dir => '/path/to/myapp/posts',
251 The run_if_script method is designed to be used at the end of the script
252 or .pm file where your application class is defined - for example:
254 ## my_web_simple_app.pl
256 use Web::Simple 'HelloWorld';
261 sub dispatch_request {
263 [ 200, [ 'Content-type', 'text/plain' ], [ 'Hello world!' ] ]
266 [ 405, [ 'Content-type', 'text/plain' ], [ 'Method not allowed' ] ]
271 HelloWorld->run_if_script;
273 This returns a true value, so your file is now valid as a module - so
275 require 'my_web_simple_app.pl';
277 my $hw = HelloWorld->new;
279 will work fine (and you can rename it to lib/HelloWorld.pm later to make it
280 a real use-able module).
282 However, it detects if it's being run as a script (via testing $0) and if
283 so attempts to do the right thing.
285 If run under a CGI environment, your application will execute as a CGI.
287 If run under a FastCGI environment, your application will execute as a
288 FastCGI process (this works both for dynamic shared-hosting-style FastCGI
289 and for apache FastCgiServer style setups).
291 If run from the commandline with a URL path, it runs a GET request against
294 $ perl -Ilib examples/hello-world/hello-world.cgi /
296 Content-Type: text/plain
300 You can also provide a method name -
302 $ perl -Ilib examples/hello-world/hello-world.cgi POST /
303 405 Method Not Allowed
304 Content-Type: text/plain
308 For a POST or PUT request, pairs on the command line will be treated
309 as form variables. For any request, pairs on the command line ending in :
310 are treated as headers, and 'Content:' will set the request body -
312 $ ./myapp POST / Accept: text/html form_field_name form_field_value
314 $ ./myapp POST / Content-Type: text/json Content: '{ "json": "here" }'
316 The body of the response is sent to STDOUT and the headers to STDERR, so
318 $ ./myapp GET / >index.html
320 will generally do the right thing.
322 To send basic authentication credentials, use user:pass@ syntax -
324 $ ./myapp GET bob:secret@/protected/path
326 Additionally, you can treat the file as though it were a standard PSGI
327 application file (*.psgi). For example you can start up up with C<plackup>
329 plackup my_web_simple_app.pl
333 starman my_web_simple_app.pl
337 This method is called by L</run_if_script> to create the L<PSGI> app coderef
338 for use via L<Plack> and L<plackup>. If you want to globally add middleware,
339 you can override this method:
341 use Web::Simple 'HelloWorld';
348 around 'to_psgi_app', sub {
349 my ($orig, $self) = (shift, shift);
350 my $app = $self->$orig(@_);
352 enable ...; ## whatever middleware you want
358 This method can also be used to mount a Web::Simple application within
359 a separate C<*.psgi> file -
367 mount '/' => WSApp->to_psgi_app;
368 mount '/another' => AnotherWSApp->to_psgi_app;
371 This method can be called as a class method, in which case it will implicitly
372 call ->new when the PSGI coderef is first invoked, or as an object method ...
373 in which case it doesn't.
377 Used for running your application under stand-alone CGI and FCGI modes.
379 I should document this more extensively but run_if_script will call it when
380 you need it, so don't worry about it too much.
382 =head2 run_test_request
384 my $res = $app->run_test_request(GET => '/' => %headers);
386 my $res = $app->run_test_request(POST => '/' => %headers_or_form);
388 my $res = $app->run_test_request($http_request);
390 Accepts either an L<HTTP::Request> object or ($method, $path) and runs that
391 request against the application, returning an L<HTTP::Response> object.
393 If the HTTP method is POST or PUT, then a series of pairs can be passed after
394 this to create a form style message body. If you need to test an upload, then
395 create an L<HTTP::Request> object by hand or use the C<POST> subroutine
396 provided by L<HTTP::Request::Common>.
398 If you prefix the URL with 'user:pass@' this will be converted into
399 an Authorization header for HTTP basic auth:
401 my $res = $app->run_test_request(
402 GET => 'bob:secret@/protected/resource'
405 If pairs are passed where the key ends in :, it is instead treated as a
408 my $res = $app->run_test_request(
410 'Accept:' => 'text/html',
411 some_form_key => 'value'
414 will do what you expect. You can also pass a special key of Content: to
415 set the request body:
417 my $res = $app->run_test_request(
419 'Content-Type:' => 'text/json',
420 'Content:' => '{ "json": "here" }',
425 See L<Web::Simple> for authors.
427 =head1 COPYRIGHT AND LICENSE
429 See L<Web::Simple> for the copyright and license.