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; };
86 return $self->_run_fcgi if
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
90 return $self->_run_cgi if $ENV{GATEWAY_INTERFACE};
91 return $self->run_cli(@ARGV);
95 my ($self, @args) = @_;
96 return if !@args || $args[0] !~ m{(^[A-Z/])|\@};
97 unshift @args, 'GET' if $args[0] !~ /^[A-Z]/;
98 $self->_run_cli_test_request(@args);
102 sub _test_request_spec_to_http_request {
103 my ($self, $method, $path, @rest) = @_;
105 # if it's a reference, assume a request object
106 return $method if ref($method);
108 if ($path =~ s/^(.*?)\@//) {
110 require MIME::Base64;
111 unshift @rest, 'Authorization:', 'Basic '.MIME::Base64::encode($basic);
114 my $request = HTTP::Request->new($method => $path);
118 while (my ($header, $value) = splice(@rest, 0, 2)) {
119 unless ($header =~ s/:$//) {
120 push @params, $header, $value;
123 if ($header eq 'Content') {
124 $request->content($value);
126 $request->headers->push_header($header, $value);
130 if (($method eq 'POST' or $method eq 'PUT') and @params) {
133 my $url = URI->new('http:');
134 $url->query_form(@params);
137 $request->header('Content-Type' => 'application/x-www-form-urlencoded');
138 $request->header('Content-Length' => length($content));
139 $request->content($content);
145 sub run_test_request {
146 my ($self, @req) = @_;
148 require HTTP::Request;
152 my $request = $self->_test_request_spec_to_http_request(@req);
154 Plack::Test::test_psgi(
155 $self->to_psgi_app, sub { shift->($request) }
159 sub _run_cli_test_request {
160 my ($self, @req) = @_;
161 my $response = $self->run_test_request(@req);
163 binmode(STDOUT); binmode(STDERR); # for win32
165 print STDERR $response->status_line."\n";
166 print STDERR $response->headers_as_string("\n")."\n";
167 my $content = $response->content;
168 $content .= "\n" if length($content) and $content !~ /\n\z/;
169 print STDOUT $content if $content;
173 my ($self, @args) = @_;
174 return $self->run_cli_request(@args) || die $self->cli_request_usage;
177 sub cli_request_usage {
178 "This application does not implement its own run_cli method. To run\n".
179 "this script in CGI test mode, pass a URL path beginning with /:\n".
189 Web::Simple::Application - A base class for your Web-Simple application
193 This is a base class for your L<Web::Simple> application. You probably don't
194 need to construct this class yourself, since L<Web::Simple> does the 'heavy
195 lifting' for you in that regards.
199 This class exposes the following public methods.
201 =head2 default_config
203 Merges with the C<config> initializer to provide configuration information for
204 your application. For example:
209 posts_dir => $FindBin::Bin.'/posts',
213 Now, the C<config> attribute of C<$self> will be set to a HashRef
214 containing keys 'title' and 'posts_dir'.
216 The keys from default_config are merged into any config supplied, so
217 if you construct your application like:
219 MyWebSimpleApp::Web->new(
220 config => { title => 'Spoon', environment => 'dev' }
223 then C<config> will contain:
227 posts_dir => '/path/to/myapp/posts',
233 The C<run_if_script> method is designed to be used at the end of the script
234 or .pm file where your application class is defined - for example:
236 ## my_web_simple_app.pl
238 use Web::Simple 'HelloWorld';
243 sub dispatch_request {
245 [ 200, [ 'Content-type', 'text/plain' ], [ 'Hello world!' ] ]
248 [ 405, [ 'Content-type', 'text/plain' ], [ 'Method not allowed' ] ]
253 HelloWorld->run_if_script;
255 This returns a true value, so your file is now valid as a module - so
257 require 'my_web_simple_app.pl';
259 my $hw = HelloWorld->new;
261 will work fine (and you can rename it to lib/HelloWorld.pm later to make it
262 a real use-able module).
264 Specifically, this true value is a PSGI app. You can you can pass the return
265 value of C<HelloWorld->run_if_script> to code expecting a PSGI app and you can
266 treat the file as though it were a standard PSGI application file (*.psgi). For
267 example you can start it up with C<plackup>
269 plackup my_web_simple_app.pl
273 starman my_web_simple_app.pl
275 If C<run_if_script> is called from a situation where there is no caller, i.e. as
276 C<perl my_web_simple_app.pl> on the shell, or by a web server, it will call the
277 C<run> method to run the actual application itself.
281 If run under a CGI environment, your application will execute as a CGI.
283 If run under a FastCGI environment, your application will execute as a
284 FastCGI process (this works both for dynamic shared-hosting-style FastCGI
285 and for apache FastCgiServer style setups).
287 If neither of these are the case, it defaults to running the C<run_cli> method
288 with C<@ARGV> as arguments.
292 This method is meant to be overriden to implement your own command line mode for
293 the app, be this a debugger, interactive mode or page generator.
295 Its default implementation calls the C<run_cli_request> method with the
296 arguments it was given, or, if that indicates failure by returning 0, calls
297 C<cli_request_usage> to print a message explaining the correct CLI usage.
299 =head2 run_cli_request
301 Looks at the arguments passed to it, typically C<@ARGV> captured somewhere up the
302 callstack, and tries to convert that into a sensible request against the
303 application, which it then runs. Any results are printed to C<STDOUT>. Returns
304 C<1> if it was able to run the request, and C<undef> if it was not able to
305 covert the arguments into a sensible request.
307 If run with a URL path, it runs a GET request against that path -
309 $ perl -Ilib examples/hello-world/hello-world.cgi /
311 Content-Type: text/plain
315 You can also provide a method name -
317 $ perl -Ilib examples/hello-world/hello-world.cgi POST /
318 405 Method Not Allowed
319 Content-Type: text/plain
323 For a POST or PUT request, pairs on the command line will be treated
324 as form variables. For any request, pairs on the command line ending in :
325 are treated as headers, and 'Content:' will set the request body -
327 $ ./myapp POST / Accept: text/html form_field_name form_field_value
329 $ ./myapp POST / Content-Type: text/json Content: '{ "json": "here" }'
331 The body of the response is sent to STDOUT and the headers to STDERR, so
333 $ ./myapp GET / >index.html
335 will generally do the right thing.
337 To send basic authentication credentials, use user:pass@ syntax -
339 $ ./myapp GET bob:secret@/protected/path
341 =head2 cli_request_usage
343 Prints a message explaining how to pass CLI parameters. Can be overridden for
348 This method is called by L</run_if_script> to create the L<PSGI> app coderef
349 for use via L<Plack> and L<plackup>. If you want to globally add middleware,
350 you can override this method:
352 use Web::Simple 'HelloWorld';
359 around 'to_psgi_app', sub {
360 my ($orig, $self) = (shift, shift);
361 my $app = $self->$orig(@_);
363 enable ...; ## whatever middleware you want
369 This method can also be used to mount a Web::Simple application within
370 a separate C<*.psgi> file -
378 mount '/' => WSApp->to_psgi_app;
379 mount '/another' => AnotherWSApp->to_psgi_app;
382 This method can be called as a class method, in which case it implicitly
383 calls ->new, or as an object method ... in which case it doesn't.
385 =head2 run_test_request
387 my $res = $app->run_test_request(GET => '/' => %headers);
389 my $res = $app->run_test_request(POST => '/' => %headers_or_form);
391 my $res = $app->run_test_request($http_request);
393 Accepts either an L<HTTP::Request> object or ($method, $path) and runs that
394 request against the application, returning an L<HTTP::Response> object.
396 If the HTTP method is POST or PUT, then a series of pairs can be passed after
397 this to create a form style message body. If you need to test an upload, then
398 create an L<HTTP::Request> object by hand or use the C<POST> subroutine
399 provided by L<HTTP::Request::Common>.
401 If you prefix the URL with 'user:pass@' this will be converted into
402 an Authorization header for HTTP basic auth:
404 my $res = $app->run_test_request(
405 GET => 'bob:secret@/protected/resource'
408 If pairs are passed where the key ends in :, it is instead treated as a
411 my $res = $app->run_test_request(
413 'Accept:' => 'text/html',
414 some_form_key => 'value'
417 will do what you expect. You can also pass a special key of Content: to
418 set the request body:
420 my $res = $app->run_test_request(
422 'Content-Type:' => 'text/json',
423 'Content:' => '{ "json": "here" }',
428 See L<Web::Simple> for authors.
430 =head1 COPYRIGHT AND LICENSE
432 See L<Web::Simple> for the copyright and license.