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 require Web::Simple::DispatchNode;
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 # ->to_psgi_app is true for require() but also works for plackup
54 return $_[0]->to_psgi_app if caller(1);
55 my $self = ref($_[0]) ? $_[0] : $_[0]->new;
61 require Plack::Handler::CGI;
62 Plack::Handler::CGI->new->run($self->to_psgi_app);
67 require Plack::Handler::FCGI;
68 Plack::Handler::FCGI->new->run($self->to_psgi_app);
72 my $self = ref($_[0]) ? $_[0] : $_[0]->new;
73 my $app = $self->_dispatcher->to_app;
75 # Close over $self to keep $self alive even though
76 # we weakened the copies the dispatcher has; the
77 # if 0 causes the ops to be optimised away to
78 # minimise the performance impact and avoid void
79 # context warnings while still doing the closing
80 # over part. As Mithaldu said: "Gnarly." ...
82 return sub { $self if 0; goto &$app; };
88 $ENV{PHP_FCGI_CHILDREN} || $ENV{FCGI_ROLE} || $ENV{FCGI_SOCKET_PATH}
89 || ( -S STDIN && !$ENV{GATEWAY_INTERFACE} )
90 # If STDIN is a socket, almost certainly FastCGI, except for mod_cgid
92 return $self->_run_fcgi;
93 } elsif ($ENV{GATEWAY_INTERFACE}) {
94 return $self->_run_cgi;
96 unless (@ARGV && $ARGV[0] =~ m{(^[A-Z/])|\@}) {
97 return $self->_run_cli(@ARGV);
102 unshift(@args, 'GET') if $args[0] !~ /^[A-Z]/;
104 $self->_run_cli_test_request(@args);
107 sub _test_request_spec_to_http_request {
108 my ($self, $method, $path, @rest) = @_;
110 # if it's a reference, assume a request object
111 return $method if ref($method);
113 if ($path =~ s/^(.*?)\@//) {
115 require MIME::Base64;
116 unshift @rest, 'Authorization:', 'Basic '.MIME::Base64::encode($basic);
119 my $request = HTTP::Request->new($method => $path);
123 while (my ($header, $value) = splice(@rest, 0, 2)) {
124 unless ($header =~ s/:$//) {
125 push @params, $header, $value;
128 if ($header eq 'Content') {
129 $request->content($value);
131 $request->headers->push_header($header, $value);
135 if (($method eq 'POST' or $method eq 'PUT') and @params) {
138 my $url = URI->new('http:');
139 $url->query_form(@params);
142 $request->header('Content-Type' => 'application/x-www-form-urlencoded');
143 $request->header('Content-Length' => length($content));
144 $request->content($content);
150 sub run_test_request {
151 my ($self, @req) = @_;
153 require HTTP::Request;
157 my $request = $self->_test_request_spec_to_http_request(@req);
159 Plack::Test::test_psgi(
160 $self->to_psgi_app, sub { shift->($request) }
164 sub _run_cli_test_request {
165 my ($self, @req) = @_;
166 my $response = $self->run_test_request(@req);
168 binmode(STDOUT); binmode(STDERR); # for win32
170 print STDERR $response->status_line."\n";
171 print STDERR $response->headers_as_string("\n")."\n";
172 my $content = $response->content;
173 $content .= "\n" if length($content) and $content !~ /\n\z/;
174 print STDOUT $content if $content;
179 die $self->_cli_usage;
183 "To run this script in CGI test mode, pass a URL path beginning with /:\n".
193 Web::Simple::Application - A base class for your Web-Simple application
197 This is a base class for your L<Web::Simple> application. You probably don't
198 need to construct this class yourself, since L<Web::Simple> does the 'heavy
199 lifting' for you in that regards.
203 This class exposes the following public methods.
205 =head2 default_config
207 Merges with the C<config> initializer to provide configuration information for
208 your application. For example:
213 posts_dir => $FindBin::Bin.'/posts',
217 Now, the C<config> attribute of C<$self> will be set to a HashRef
218 containing keys 'title' and 'posts_dir'.
220 The keys from default_config are merged into any config supplied, so
221 if you construct your application like:
223 MyWebSimpleApp::Web->new(
224 config => { title => 'Spoon', environment => 'dev' }
227 then C<config> will contain:
231 posts_dir => '/path/to/myapp/posts',
237 The run_if_script method is designed to be used at the end of the script
238 or .pm file where your application class is defined - for example:
240 ## my_web_simple_app.pl
242 use Web::Simple 'HelloWorld';
247 sub dispatch_request {
249 [ 200, [ 'Content-type', 'text/plain' ], [ 'Hello world!' ] ]
252 [ 405, [ 'Content-type', 'text/plain' ], [ 'Method not allowed' ] ]
257 HelloWorld->run_if_script;
259 This returns a true value, so your file is now valid as a module - so
261 require 'my_web_simple_app.pl';
263 my $hw = HelloWorld->new;
265 will work fine (and you can rename it to lib/HelloWorld.pm later to make it
266 a real use-able module).
268 However, it detects if it's being run as a script (via testing $0) and if
269 so attempts to do the right thing.
271 If run under a CGI environment, your application will execute as a CGI.
273 If run under a FastCGI environment, your application will execute as a
274 FastCGI process (this works both for dynamic shared-hosting-style FastCGI
275 and for apache FastCgiServer style setups).
277 If run from the commandline with a URL path, it runs a GET request against
280 $ perl -Ilib examples/hello-world/hello-world.cgi /
282 Content-Type: text/plain
286 You can also provide a method name -
288 $ perl -Ilib examples/hello-world/hello-world.cgi POST /
289 405 Method Not Allowed
290 Content-Type: text/plain
294 For a POST or PUT request, pairs on the command line will be treated
295 as form variables. For any request, pairs on the command line ending in :
296 are treated as headers, and 'Content:' will set the request body -
298 $ ./myapp POST / Accept: text/html form_field_name form_field_value
300 $ ./myapp POST / Content-Type: text/json Content: '{ "json": "here" }'
302 The body of the response is sent to STDOUT and the headers to STDERR, so
304 $ ./myapp GET / >index.html
306 will generally do the right thing.
308 To send basic authentication credentials, use user:pass@ syntax -
310 $ ./myapp GET bob:secret@/protected/path
312 Additionally, you can treat the file as though it were a standard PSGI
313 application file (*.psgi). For example you can start up up with C<plackup>
315 plackup my_web_simple_app.pl
319 starman my_web_simple_app.pl
323 This method is called by L</run_if_script> to create the L<PSGI> app coderef
324 for use via L<Plack> and L<plackup>. If you want to globally add middleware,
325 you can override this method:
327 use Web::Simple 'HelloWorld';
334 around 'to_psgi_app', sub {
335 my ($orig, $self) = (shift, shift);
336 my $app = $self->$orig(@_);
338 enable ...; ## whatever middleware you want
344 This method can also be used to mount a Web::Simple application within
345 a separate C<*.psgi> file -
353 mount '/' => WSApp->to_psgi_app;
354 mount '/another' => AnotherWSApp->to_psgi_app;
357 This method can be called as a class method, in which case it implicitly
358 calls ->new, or as an object method ... in which case it doesn't.
362 Used for running your application under stand-alone CGI and FCGI modes.
364 I should document this more extensively but run_if_script will call it when
365 you need it, so don't worry about it too much.
367 =head2 run_test_request
369 my $res = $app->run_test_request(GET => '/' => %headers);
371 my $res = $app->run_test_request(POST => '/' => %headers_or_form);
373 my $res = $app->run_test_request($http_request);
375 Accepts either an L<HTTP::Request> object or ($method, $path) and runs that
376 request against the application, returning an L<HTTP::Response> object.
378 If the HTTP method is POST or PUT, then a series of pairs can be passed after
379 this to create a form style message body. If you need to test an upload, then
380 create an L<HTTP::Request> object by hand or use the C<POST> subroutine
381 provided by L<HTTP::Request::Common>.
383 If you prefix the URL with 'user:pass@' this will be converted into
384 an Authorization header for HTTP basic auth:
386 my $res = $app->run_test_request(
387 GET => 'bob:secret@/protected/resource'
390 If pairs are passed where the key ends in :, it is instead treated as a
393 my $res = $app->run_test_request(
395 'Accept:' => 'text/html',
396 some_form_key => 'value'
399 will do what you expect. You can also pass a special key of Content: to
400 set the request body:
402 my $res = $app->run_test_request(
404 'Content-Type:' => 'text/json',
405 'Content:' => '{ "json": "here" }',
410 See L<Web::Simple> for authors.
412 =head1 COPYRIGHT AND LICENSE
414 See L<Web::Simple> for the copyright and license.