1 package Web::Simple::Application;
3 use Scalar::Util 'weaken';
11 +{ $self->default_config }
14 my ($self, $value) = @_;
15 my %default = $self->default_config;
16 my @not = grep !exists $value->{$_}, keys %default;
17 @{$value}{@not} = @default{@not};
21 sub default_config { () }
23 has '_dispatcher' => (is => 'lazy');
25 sub _build__dispatcher {
27 require Web::Dispatch;
28 my $final = $self->_build_final_dispatcher;
30 # We need to weaken both the copy of $self that the
31 # app parameter will close over and the copy that'll
32 # be passed through as a node argument.
34 # To ensure that this doesn't then result in us being
35 # DESTROYed unexpectedly early, our to_psgi_app method
36 # closes back over $self
40 dispatch_app => sub { $self->dispatch_request(@_), $final },
41 dispatch_object => $self
43 weaken($dispatch_args{dispatch_object});
44 Web::Dispatch->new(%dispatch_args);
47 sub _build_final_dispatcher {
48 [ 404, [ 'Content-type', 'text/plain' ], [ 'Not found' ] ]
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;
60 require Plack::Handler::CGI;
61 Plack::Handler::CGI->new->run($self->to_psgi_app);
66 require Plack::Handler::FCGI;
67 Plack::Handler::FCGI->new->run($self->to_psgi_app);
71 my $self = ref($_[0]) ? $_[0] : $_[0]->new;
72 my $app = $self->_dispatcher->to_app;
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." ...
81 return sub { $self if 0; goto &$app; };
87 $ENV{PHP_FCGI_CHILDREN} || $ENV{FCGI_ROLE} || $ENV{FCGI_SOCKET_PATH}
88 || ( -S STDIN && !$ENV{GATEWAY_INTERFACE} )
89 # If STDIN is a socket, almost certainly FastCGI, except for mod_cgid
91 return $self->_run_fcgi;
92 } elsif ($ENV{GATEWAY_INTERFACE}) {
93 return $self->_run_cgi;
95 unless (@ARGV && $ARGV[0] =~ m{(^[A-Z/])|\@}) {
96 return $self->_run_cli(@ARGV);
101 unshift(@args, 'GET') if $args[0] !~ /^[A-Z]/;
103 $self->_run_cli_test_request(@args);
106 sub _test_request_spec_to_http_request {
107 my ($self, $method, $path, @rest) = @_;
109 # if it's a reference, assume a request object
110 return $method if ref($method);
112 if ($path =~ s/^(.*?)\@//) {
114 require MIME::Base64;
115 unshift @rest, 'Authorization:', 'Basic '.MIME::Base64::encode($basic);
118 my $request = HTTP::Request->new($method => $path);
122 while (my ($header, $value) = splice(@rest, 0, 2)) {
123 unless ($header =~ s/:$//) {
124 push @params, $header, $value;
127 if ($header eq 'Content') {
128 $request->content($value);
130 $request->headers->push_header($header, $value);
134 if (($method eq 'POST' or $method eq 'PUT') and @params) {
137 my $url = URI->new('http:');
138 $url->query_form(@params);
141 $request->header('Content-Type' => 'application/x-www-form-urlencoded');
142 $request->header('Content-Length' => length($content));
143 $request->content($content);
149 sub run_test_request {
150 my ($self, @req) = @_;
152 require HTTP::Request;
156 my $request = $self->_test_request_spec_to_http_request(@req);
158 Plack::Test::test_psgi(
159 $self->to_psgi_app, sub { shift->($request) }
163 sub _run_cli_test_request {
164 my ($self, @req) = @_;
165 my $response = $self->run_test_request(@req);
167 binmode(STDOUT); binmode(STDERR); # for win32
169 print STDERR $response->status_line."\n";
170 print STDERR $response->headers_as_string("\n")."\n";
171 my $content = $response->content;
172 $content .= "\n" if length($content) and $content !~ /\n\z/;
173 print STDOUT $content if $content;
178 die $self->_cli_usage;
182 "To run this script in CGI test mode, pass a URL path beginning with /:\n".
192 Web::Simple::Application - A base class for your Web-Simple application
196 This is a base class for your L<Web::Simple> application. You probably don't
197 need to construct this class yourself, since L<Web::Simple> does the 'heavy
198 lifting' for you in that regards.
202 This class exposes the following public methods.
204 =head2 default_config
206 Merges with the C<config> initializer to provide configuration information for
207 your application. For example:
212 posts_dir => $FindBin::Bin.'/posts',
216 Now, the C<config> attribute of C<$self> will be set to a HashRef
217 containing keys 'title' and 'posts_dir'.
219 The keys from default_config are merged into any config supplied, so
220 if you construct your application like:
222 MyWebSimpleApp::Web->new(
223 config => { title => 'Spoon', environment => 'dev' }
226 then C<config> will contain:
230 posts_dir => '/path/to/myapp/posts',
236 The run_if_script method is designed to be used at the end of the script
237 or .pm file where your application class is defined - for example:
239 ## my_web_simple_app.pl
241 use Web::Simple 'HelloWorld';
246 sub dispatch_request {
248 [ 200, [ 'Content-type', 'text/plain' ], [ 'Hello world!' ] ]
251 [ 405, [ 'Content-type', 'text/plain' ], [ 'Method not allowed' ] ]
256 HelloWorld->run_if_script;
258 This returns a true value, so your file is now valid as a module - so
260 require 'my_web_simple_app.pl';
262 my $hw = HelloWorld->new;
264 will work fine (and you can rename it to lib/HelloWorld.pm later to make it
265 a real use-able module).
267 However, it detects if it's being run as a script (via testing $0) and if
268 so attempts to do the right thing.
270 If run under a CGI environment, your application will execute as a CGI.
272 If run under a FastCGI environment, your application will execute as a
273 FastCGI process (this works both for dynamic shared-hosting-style FastCGI
274 and for apache FastCgiServer style setups).
276 If run from the commandline with a URL path, it runs a GET request against
279 $ perl -Ilib examples/hello-world/hello-world.cgi /
281 Content-Type: text/plain
285 You can also provide a method name -
287 $ perl -Ilib examples/hello-world/hello-world.cgi POST /
288 405 Method Not Allowed
289 Content-Type: text/plain
293 For a POST or PUT request, pairs on the command line will be treated
294 as form variables. For any request, pairs on the command line ending in :
295 are treated as headers, and 'Content:' will set the request body -
297 $ ./myapp POST / Accept: text/html form_field_name form_field_value
299 $ ./myapp POST / Content-Type: text/json Content: '{ "json": "here" }'
301 The body of the response is sent to STDOUT and the headers to STDERR, so
303 $ ./myapp GET / >index.html
305 will generally do the right thing.
307 To send basic authentication credentials, use user:pass@ syntax -
309 $ ./myapp GET bob:secret@/protected/path
311 Additionally, you can treat the file as though it were a standard PSGI
312 application file (*.psgi). For example you can start up up with C<plackup>
314 plackup my_web_simple_app.pl
318 starman my_web_simple_app.pl
322 This method is called by L</run_if_script> to create the L<PSGI> app coderef
323 for use via L<Plack> and L<plackup>. If you want to globally add middleware,
324 you can override this method:
326 use Web::Simple 'HelloWorld';
333 around 'to_psgi_app', sub {
334 my ($orig, $self) = (shift, shift);
335 my $app = $self->$orig(@_);
337 enable ...; ## whatever middleware you want
343 This method can also be used to mount a Web::Simple application within
344 a separate C<*.psgi> file -
352 mount '/' => WSApp->to_psgi_app;
353 mount '/another' => AnotherWSApp->to_psgi_app;
356 This method can be called as a class method, in which case it implicitly
357 calls ->new, or as an object method ... in which case it doesn't.
361 Used for running your application under stand-alone CGI and FCGI modes.
363 I should document this more extensively but run_if_script will call it when
364 you need it, so don't worry about it too much.
366 =head2 run_test_request
368 my $res = $app->run_test_request(GET => '/' => %headers);
370 my $res = $app->run_test_request(POST => '/' => %headers_or_form);
372 my $res = $app->run_test_request($http_request);
374 Accepts either an L<HTTP::Request> object or ($method, $path) and runs that
375 request against the application, returning an L<HTTP::Response> object.
377 If the HTTP method is POST or PUT, then a series of pairs can be passed after
378 this to create a form style message body. If you need to test an upload, then
379 create an L<HTTP::Request> object by hand or use the C<POST> subroutine
380 provided by L<HTTP::Request::Common>.
382 If you prefix the URL with 'user:pass@' this will be converted into
383 an Authorization header for HTTP basic auth:
385 my $res = $app->run_test_request(
386 GET => 'bob:secret@/protected/resource'
389 If pairs are passed where the key ends in :, it is instead treated as a
392 my $res = $app->run_test_request(
394 'Accept:' => 'text/html',
395 some_form_key => 'value'
398 will do what you expect. You can also pass a special key of Content: to
399 set the request body:
401 my $res = $app->run_test_request(
403 'Content-Type:' => 'text/json',
404 'Content:' => '{ "json": "here" }',
409 See L<Web::Simple> for authors.
411 =head1 COPYRIGHT AND LICENSE
413 See L<Web::Simple> for the copyright and license.