some doc cleanup
[catagits/Web-Simple.git] / lib / Web / Simple.pm
CommitLineData
5c33dda5 1package Web::Simple;
2
8bd060f4 3use strictures 1;
8c4ffad3 4use 5.008;
8bd060f4 5use warnings::illegalproto ();
876e62e1 6use Moo ();
7use Web::Dispatch::Wrapper ();
8c4ffad3 8
1cf4503c 9our $VERSION = '0.020';
5c33dda5 10
44db8e76 11sub import {
5c33dda5 12 my ($class, $app_package) = @_;
876e62e1 13 $app_package ||= caller;
14 $class->_export_into($app_package);
15 eval "package $app_package; use Web::Dispatch::Wrapper; use Moo; 1"
16 or die "Failed to setup app package: $@";
445b3ea0 17 strictures->import;
8bd060f4 18 warnings::illegalproto->unimport;
5c33dda5 19}
20
21sub _export_into {
22 my ($class, $app_package) = @_;
23 {
24 no strict 'refs';
c7b1c57f 25 *{"${app_package}::PSGI_ENV"} = sub () { -1 };
5c33dda5 26 require Web::Simple::Application;
27 unshift(@{"${app_package}::ISA"}, 'Web::Simple::Application');
28 }
b7063124 29 (my $name = $app_package) =~ s/::/\//g;
30 $INC{"${name}.pm"} = 'Set by "use Web::Simple;" invocation';
5c33dda5 31}
32
fd6d986e 331;
34823486 34
7401408e 35=head1 NAME
36
37Web::Simple - A quick and easy way to build simple web applications
38
7401408e 39
40=head1 SYNOPSIS
41
05ad188d 42 #!/usr/bin/env perl
7401408e 43
4f83bde7 44 package HelloWorld;
6ee6b2dc 45 use Web::Simple;
4f83bde7 46
47 sub dispatch_request {
48 sub (GET) {
49 [ 200, [ 'Content-type', 'text/plain' ], [ 'Hello world!' ] ]
50 },
51 sub () {
52 [ 405, [ 'Content-type', 'text/plain' ], [ 'Method not allowed' ] ]
445b3ea0 53 }
7401408e 54 }
55
56 HelloWorld->run_if_script;
57
05ad188d 58If you save this file into your cgi-bin as C<hello-world.cgi> and then visit:
7401408e 59
60 http://my.server.name/cgi-bin/hello-world.cgi/
61
4f83bde7 62you'll get the "Hello world!" string output to your browser. At the same time
63this file will also act as a class module, so you can save it as HelloWorld.pm
64and use it as-is in test scripts or other deployment mechanisms.
65
ca30a017 66Note that you should retain the ->run_if_script even if your app is a
67module, since this additionally makes it valid as a .psgi file, which can
68be extremely useful during development.
69
4f83bde7 70For more complex examples and non-CGI deployment, see
71L<Web::Simple::Deployment>. To get help with L<Web::Simple>, please connect to
72the irc.perl.org IRC network and join #web-simple.
7401408e 73
fb771406 74=head1 DESCRIPTION
7401408e 75
6a4808bf 76The philosophy of L<Web::Simple> is to keep to an absolute bare minimum for
7401408e 77everything. It is not designed to be used for large scale applications;
78the L<Catalyst> web framework already works very nicely for that and is
79a far more mature, well supported piece of software.
80
81However, if you have an application that only does a couple of things, and
3895385d 82want to not have to think about complexities of deployment, then L<Web::Simple>
7401408e 83might be just the thing for you.
84
6a4808bf 85The only public interface the L<Web::Simple> module itself provides is an
86C<import> based one:
7401408e 87
88 use Web::Simple 'NameOfApplication';
89
6a4808bf 90This sets up your package (in this case "NameOfApplication" is your package)
3895385d 91so that it inherits from L<Web::Simple::Application> and imports L<strictures>,
38d5b336 92as well as installs a C<PSGI_ENV> constant for convenience, as well as some
3895385d 93other subroutines.
94
6a4808bf 95Importing L<strictures> will automatically make your code use the C<strict> and
3895385d 96C<warnings> pragma, so you can skip the usual:
7401408e 97
98 use strict;
3895385d 99 use warnings FATAL => 'aa';
7401408e 100
101provided you 'use Web::Simple' at the top of the file. Note that we turn
102on *fatal* warnings so if you have any warnings at any point from the file
103that you did 'use Web::Simple' in, then your application will die. This is,
104so far, considered a feature.
105
a5006b25 106When we inherit from L<Web::Simple::Application> we also use L<Moo>, which is
3895385d 107the the equivalent of:
7401408e 108
109 {
110 package NameOfApplication;
445b3ea0 111 use Moo;
112 extends 'Web::Simple::Application';
7401408e 113 }
114
6a4808bf 115So you can use L<Moo> features in your application, such as creating attributes
116using the C<has> subroutine, etc. Please see the documentation for L<Moo> for
117more information.
118
445b3ea0 119It also exports the following subroutines for use in dispatchers:
7401408e 120
74afe4b7 121 response_filter { ... };
7401408e 122
123 redispatch_to '/somewhere';
124
b7063124 125Finally, import sets
126
127 $INC{"NameOfApplication.pm"} = 'Set by "use Web::Simple;" invocation';
128
129so that perl will not attempt to load the application again even if
130
131 require NameOfApplication;
132
133is encountered in other code.
134
3583ca04 135=head1 DISPATCH STRATEGY
136
6a4808bf 137L<Web::Simple> despite being straightforward to use, has a powerful system
3895385d 138for matching all sorts of incoming URLs to one or more subroutines. These
139subroutines can be simple actions to take for a given URL, or something
140more complicated, including entire L<Plack> applications, L<Plack::Middleware>
141and nested subdispatchers.
142
c21c9f07 143=head2 Examples
144
445b3ea0 145 sub dispatch_request {
c21c9f07 146 # matches: GET /user/1.htm?show_details=1
147 # GET /user/1.htm
148 sub (GET + /user/* + ?show_details~ + .htm|.html|.xhtml) {
c254b30e 149 my ($self, $user_id, $show_details) = @_;
c21c9f07 150 ...
151 },
152 # matches: POST /user?username=frew
153 # POST /user?username=mst&first_name=matt&last_name=trout
154 sub (POST + /user + ?username=&*) {
c254b30e 155 my ($self, $username, $misc_params) = @_;
c21c9f07 156 ...
157 },
158 # matches: DELETE /user/1/friend/2
159 sub (DELETE + /user/*/friend/*) {
c254b30e 160 my ($self, $user_id, $friend_id) = @_;
c21c9f07 161 ...
162 },
163 # matches: PUT /user/1?first_name=Matt&last_name=Trout
164 sub (PUT + /user/* + ?first_name~&last_name~) {
c254b30e 165 my ($self, $user_id, $first_name, $last_name) = @_;
c21c9f07 166 ...
167 },
168 sub (/user/*/...) {
445b3ea0 169 my $user_id = $_[1];
170 # matches: PUT /user/1/role/1
171 sub (PUT + /role/*) {
172 my $role_id = $_[1];
173 ...
174 },
175 # matches: DELETE /user/1/role/1
176 sub (DELETE + /role/*) {
177 my $role_id = $_[1];
178 ...
179 },
c21c9f07 180 },
181 }
182
3706e2a0 183=head2 The dispatch cycle
81a5b03e 184
3706e2a0 185At the beginning of a request, your app's dispatch_request method is called
186with the PSGI $env as an argument. You can handle the request entirely in
187here and return a PSGI response arrayref if you want:
81a5b03e 188
3706e2a0 189 sub dispatch_request {
190 my ($self, $env) = @_;
191 [ 404, [ 'Content-type' => 'text/plain' ], [ 'Amnesia == fail' ] ]
192 }
81a5b03e 193
3706e2a0 194However, generally, instead of that, you return a set of dispatch subs:
81a5b03e 195
3706e2a0 196 sub dispatch_request {
197 my $self = shift;
198 sub (/) { redispatch_to '/index.html' },
199 sub (/user/*) { $self->show_user($_[1]) },
200 ...
201 }
81a5b03e 202
e927492b 203Well, a sub is a valid PSGI response too (for ultimate streaming and async
204cleverness). If you want to return a PSGI sub you have to wrap it into an
205array ref.
206
207 sub dispatch_request {
208 [ sub {
209 my $respond = shift;
210 # This is pure PSGI here, so read perldoc PSGI
211 } ]
212 }
213
3706e2a0 214If you return a subroutine with a prototype, the prototype is treated
215as a match specification - and if the test is passed, the body of the
65e03df0 216sub is called as a method and passed any matched arguments (see below for more details).
81a5b03e 217
65e03df0 218You can also return a plain subroutine which will be called with just C<$env>
219- remember that in this case if you need C<$self> you B<must> close over it.
81a5b03e 220
3895385d 221If you return a normal object, L<Web::Simple> will simply return it upwards on
222the assumption that a response_filter (or some arbitrary L<Plack::Middleware>)
223somewhere will convert it to something useful. This allows:
81a5b03e 224
3706e2a0 225 sub dispatch_request {
226 my $self = shift;
227 sub (.html) { response_filter { $self->render_zoom($_[0]) } },
228 sub (/user/*) { $self->users->get($_[1]) },
229 }
81a5b03e 230
3895385d 231to render a user object to HTML, if there is an incoming URL such as:
232
233 http://myweb.org/user/111.html
234
235This works because as we descend down the dispachers, we first match
236C<sub (.html)>, which adds a C<response_filter> (basically a specialized routine
237that follows the L<Plack::Middleware> specification), and then later we also
238match C<sub (/user/*)> which gets a user and returns that as the response.
239This user object 'bubbles up' through all the wrapping middleware until it hits
240the C<response_filter> we defined, after which the return is converted to a
241true html response.
81a5b03e 242
65e03df0 243However, two types of object are treated specially - a C<Plack::Component> object
244will have its C<to_app> method called and be used as a dispatcher:
81a5b03e 245
3706e2a0 246 sub dispatch_request {
247 my $self = shift;
248 sub (/static/...) { Plack::App::File->new(...) },
249 ...
81a5b03e 250 }
251
65e03df0 252A L<Plack::Middleware> object will be used as a filter for the rest of the
3706e2a0 253dispatch being returned into:
81a5b03e 254
6af22ff2 255 ## responds to /admin/track_usage AND /admin/delete_accounts
256
3706e2a0 257 sub dispatch_request {
258 my $self = shift;
6af22ff2 259 sub (/admin/**) {
260 Plack::Middleware::Session->new(%opts);
261 },
262 sub (/admin/track_usage) {
263 ## something that needs a session
264 },
265 sub (/admin/delete_accounts) {
266 ## something else that needs a session
267 },
81a5b03e 268 }
269
65e03df0 270Note that this is for the dispatch being B<returned> to, so if you want to
3706e2a0 271provide it inline you need to do:
81a5b03e 272
6af22ff2 273 ## ALSO responds to /admin/track_usage AND /admin/delete_accounts
274
3706e2a0 275 sub dispatch_request {
276 my $self = shift;
3706e2a0 277 sub (/admin/...) {
6af22ff2 278 sub {
279 Plack::Middleware::Session->new(%opts);
280 },
281 sub (/track_usage) {
282 ## something that needs a session
283 },
284 sub (/delete_accounts) {
285 ## something else that needs a session
286 },
3706e2a0 287 }
81a5b03e 288 }
289
3706e2a0 290And that's it - but remember that all this happens recursively - it's
3895385d 291dispatchers all the way down. A URL incoming pattern will run all matching
292dispatchers and then hit all added filters or L<Plack::Middleware>.
3706e2a0 293
81a5b03e 294=head2 Web::Simple match specifications
295
296=head3 Method matches
297
93e30ba3 298 sub (GET) {
15dfe701 299
300A match specification beginning with a capital letter matches HTTP requests
301with that request method.
302
81a5b03e 303=head3 Path matches
304
15dfe701 305 sub (/login) {
306
307A match specification beginning with a / is a path match. In the simplest
308case it matches a specific path. To match a path with a wildcard part, you
309can do:
310
311 sub (/user/*) {
312 $self->handle_user($_[1])
313
314This will match /user/<anything> where <anything> does not include a literal
315/ character. The matched part becomes part of the match arguments. You can
316also match more than one part:
317
318 sub (/user/*/*) {
319 my ($self, $user_1, $user_2) = @_;
320
321 sub (/domain/*/user/*) {
322 my ($self, $domain, $user) = @_;
323
65e03df0 324and so on. To match an arbitrary number of parts, use C<**>:
15dfe701 325
326 sub (/page/**) {
1d02a8ae 327 my ($self, $match) = @_;
15dfe701 328
1d02a8ae 329This will result in a single element for the entire match. Note that you can do
15dfe701 330
331 sub (/page/**/edit) {
332
333to match an arbitrary number of parts up to but not including some final
334part.
335
65e03df0 336Note: Since Web::Simple handles a concept of file extensions, C<*> and C<**>
e060a690 337matchers will not by default match things after a final dot, and this
65e03df0 338can be modified by using C<*.*> and C<**.*> in the final position, e.g.:
e060a690 339
340 /one/* matches /one/two.three and captures "two"
341 /one/*.* matches /one/two.three and captures "two.three"
342 /** matches /one/two.three and captures "one/two"
343 /**.* matches /one/two.three and captures "one/two.three"
344
da8429c9 345Finally,
346
347 sub (/foo/...) {
348
65e03df0 349Will match C</foo/> on the beginning of the path B<and> strip it. This is
e060a690 350designed to be used to construct nested dispatch structures, but can also prove
351useful for having e.g. an optional language specification at the start of a
352path.
da8429c9 353
354Note that the '...' is a "maybe something here, maybe not" so the above
355specification will match like this:
356
357 /foo # no match
358 /foo/ # match and strip path to '/'
359 /foo/bar/baz # match and strip path to '/bar/baz'
360
e060a690 361Almost the same,
15e679c1 362
e060a690 363 sub (/foo...) {
364
365Will match on C</foo/bar/baz>, but also include C</foo>. Otherwise it
366operates the same way as C</foo/...>.
367
368 /foo # match and strip path to ''
369 /foo/ # match and strip path to '/'
370 /foo/bar/baz # match and strip path to '/bar/baz'
371
372Please note the difference between C<sub(/foo/...)> and C<sub(/foo...)>. In
373the first case, this is expecting to find something after C</foo> (and fails to
374match if nothing is found), while in the second case we can match both C</foo>
375and C</foo/more/to/come>. The following are roughly the same:
376
377 sub (/foo) { 'I match /foo' },
378 sub (/foo/...) {
379 sub (/bar) { 'I match /foo/bar' },
380 sub (/*) { 'I match /foo/{id}' },
381 }
382
383Versus
384
385 sub (/foo...) {
386 sub (~) { 'I match /foo' },
387 sub (/bar) { 'I match /foo/bar' },
388 sub (/*) { 'I match /foo/{id}' },
389 }
390
391You may prefer the latter example should you wish to take advantage of
392subdispatchers to scope common activities. For example:
393
394 sub (/user...) {
395 my $user_rs = $schema->resultset('User');
396 sub (~) { $user_rs },
397 sub (/*) { $user_rs->find($_[1]) },
398 }
399
400You should note the special case path match C<sub (~)> which is only meaningful
401when it is contained in this type of path match. It matches to an empty path.
402
7c03cd61 403=head4 Naming your patch matches
404
65e03df0 405Any C<*>, C<**>, C<*.*>, or C<**.*> match can be followed with C<:name> to make it into a named
7c03cd61 406match, so:
407
408 sub (/*:one/*:two/*:three/*:four) {
409 "I match /1/2/3/4 capturing { one => 1, two => 2, three => 3, four => 4 }"
410 }
411
412 sub (/**.*:allofit) {
413 "I match anything capturing { allofit => \$whole_path }"
414 }
415
416In the specific case of a simple single-* match, the * may be omitted, to
417allow you to write:
418
419 sub (/:one/:two/:three/:four) {
420 "I match /1/2/3/4 capturing { one => 1, two => 2, three => 3, four => 4 }"
421 }
422
e060a690 423=head4 C</foo> and C</foo/> are different specs
424
425As you may have noticed with the difference between C<sub(/foo/...)> and
426C<sub(/foo...)>, trailing slashes in path specs are significant. This is
427intentional and necessary to retain the ability to use relative links on
428websites. Let's demonstrate on this link:
429
430 <a href="bar">bar</a>
431
432If the user loads the url C</foo/> and clicks on this link, they will be
433sent to C</foo/bar>. However when they are on the url C</foo> and click this
434link, then they will be sent to C</bar>.
435
436This makes it necessary to be explicit about the trailing slash.
15e679c1 437
81a5b03e 438=head3 Extension matches
439
15dfe701 440 sub (.html) {
441
6a4808bf 442will match .html from the path (assuming the subroutine itself returns
65e03df0 443something, of course). This is normally used for rendering - e.g.:
15dfe701 444
445 sub (.html) {
74afe4b7 446 response_filter { $self->render_html($_[1]) }
15dfe701 447 }
448
b8bd7bd1 449Additionally,
450
451 sub (.*) {
452
6a4808bf 453will match any extension and supplies the extension as a match argument.
b8bd7bd1 454
9b9866ae 455=head3 Query and body parameter matches
456
457Query and body parameters can be match via
458
459 sub (?<param spec>) { # match URI query
460 sub (%<param spec>) { # match body params
461
cb12d2a3 462The body spec will match if the request content is either
463application/x-www-form-urlencoded or multipart/form-data - the latter
c32b7fda 464of which is required for uploads - see below.
9b9866ae 465
65e03df0 466The param spec is elements of one of the following forms:
9b9866ae 467
468 param~ # optional parameter
469 param= # required parameter
470 @param~ # optional multiple parameter
471 @param= # required multiple parameter
eb9e0e25 472 :param~ # optional parameter in hashref
473 :param= # required parameter in hashref
474 :@param~ # optional multiple in hashref
475 :@param= # required multiple in hashref
476 * # include all other parameters in hashref
477 @* # include all other parameters as multiple in hashref
9b9866ae 478
65e03df0 479separated by the C<&> character. The arguments added to the request are
480one per non-C<:>/C<*> parameter (scalar for normal, arrayref for multiple),
481plus if any C<:>/C<*> specs exist a hashref containing those values.
9b9866ae 482
3895385d 483Please note that if you specify a multiple type parameter match, you are
484ensured of getting an arrayref for the value, EVEN if the current incoming
485request has only one value. However if a parameter is specified as single
486and multiple values are found, the last one will be used.
487
65e03df0 488For example to match a C<page> parameter with an optional C<order_by> parameter one
9b9866ae 489would write:
490
491 sub (?page=&order_by~) {
eb9e0e25 492 my ($self, $page, $order_by) = @_;
493 return unless $page =~ /^\d+$/;
494 $page ||= 'id';
9b9866ae 495 response_filter {
496 $_[1]->search_rs({}, $p);
497 }
498 }
499
500to implement paging and ordering against a L<DBIx::Class::ResultSet> object.
501
3895385d 502Another Example: To get all parameters as a hashref of arrayrefs, write:
eb9e0e25 503
504 sub(?@*) {
505 my ($self, $params) = @_;
506 ...
507
8c4ffad3 508To get two parameters as a hashref, write:
509
510 sub(?:user~&:domain~) {
511 my ($self, $params) = @_; # params contains only 'user' and 'domain' keys
512
513You can also mix these, so:
514
515 sub (?foo=&@bar~&:coffee=&@*) {
516 my ($self, $foo, $bar, $params);
517
518where $bar is an arrayref (possibly an empty one), and $params contains
65e03df0 519arrayref values for all parameters B<not> mentioned and a scalar value for
8c4ffad3 520the 'coffee' parameter.
521
3895385d 522Note, in the case where you combine arrayref, single parameter and named
523hashref style, the arrayref and single parameters will appear in C<@_> in the
38d5b336 524order you defined them in the protoype, but all hashrefs will merge into a
3895385d 525single C<$params>, as in the example above.
526
1d2f4b67 527=head3 Upload matches
05aafc1a 528
529 sub (*foo=) { # param specifier can be anything valid for query or body
530
531The upload match system functions exactly like a query/body match, except
532that the values returned (if any) are C<Web::Dispatch::Upload> objects.
533
534Note that this match type will succeed in two circumstances where you might
535not expect it to - first, when the field exists but is not an upload field
536and second, when the field exists but the form is not an upload form (i.e.
537content type "application/x-www-form-urlencoded" rather than
538"multipart/form-data"). In either of these cases, what you'll get back is
539a C<Web::Dispatch::NotAnUpload> object, which will C<die> with an error
540pointing out the problem if you try and use it. To be sure you have a real
541upload object, call
542
543 $upload->is_upload # returns 1 on a valid upload, 0 on a non-upload field
544
545and to get the reason why such an object is not an upload, call
546
547 $upload->reason # returns a reason or '' on a valid upload.
548
549Other than these two methods, the upload object provides the same interface
550as L<Plack::Request::Upload> with the addition of a stringify to the temporary
551filename to make copying it somewhere else easier to handle.
552
81a5b03e 553=head3 Combining matches
554
15dfe701 555Matches may be combined with the + character - e.g.
556
b8bd7bd1 557 sub (GET + /user/*) {
558
559to create an AND match. They may also be combined withe the | character - e.g.
560
561 sub (GET|POST) {
562
563to create an OR match. Matches can be nested with () - e.g.
564
565 sub ((GET|POST) + /user/*) {
566
567and negated with ! - e.g.
568
569 sub (!/user/foo + /user/*) {
570
571! binds to the immediate rightmost match specification, so if you want
572to negate a combination you will need to use
573
574 sub ( !(POST|PUT|DELETE) ) {
575
576and | binds tighter than +, so
577
578 sub ((GET|POST) + /user/*) {
579
580and
581
582 sub (GET|POST + /user/*) {
583
584are equivalent, but
585
1760e999 586 sub ((GET + /admin/...) | (POST + /admin/...)) {
b8bd7bd1 587
588and
589
1760e999 590 sub (GET + /admin/... | POST + /admin/...) {
b8bd7bd1 591
592are not - the latter is equivalent to
593
1760e999 594 sub (GET + (/admin/...|POST) + /admin/...) {
b8bd7bd1 595
3895385d 596which will never match!
b8bd7bd1 597
598=head3 Whitespace
15dfe701 599
65e03df0 600Note that for legibility you are permitted to use whitespace:
15dfe701 601
44db8e76 602 sub (GET + /user/*) {
15dfe701 603
b8bd7bd1 604but it will be ignored. This is because the perl parser strips whitespace
605from subroutine prototypes, so this is equivalent to
606
607 sub (GET+/user/*) {
15dfe701 608
1fc9b979 609=head3 Accessing parameters via C<%_>
610
611If your dispatch specification causes your dispatch subroutine to receive
612a hash reference as its first argument, the contained named parameters
613will be accessible via C<%_>.
614
65e03df0 615This can be used to access your path matches, if they are named:
1fc9b979 616
617 sub (GET + /foo/:path_part) {
618 [ 200,
619 ['Content-type' => 'text/plain'],
620 ["We are in $_{path_part}"],
621 ];
622 }
623
624Or, if your first argument would be a hash reference containing named
625query parameters:
626
627 sub (GET + /foo + ?:some_param=) {
628 [ 200,
629 ['Content-type' => 'text/plain'],
630 ["We received $_{some_param} as parameter"],
631 ];
632 }
633
634Of course this also works when all you are doing is slurping the whole set
635of parameters by their name:
636
637 sub (GET + /foo + ?*) {
638 [ 200,
639 ['Content-type' => 'text/plain'],
640 [exists($_{foo}) ? "Received a foo: $_{foo}" : "No foo!"],
641 ],
642 }
643
65e03df0 644Note that only the first hash reference will be available via C<%_>. If
1fc9b979 645you receive additional hash references, you will need to access them as
646usual.
647
24175cb5 648=head3 Accessing the PSGI env hash
649
3706e2a0 650In some cases you may wish to get the raw PSGI env hash - to do this,
65e03df0 651you can either use a plain sub:
3706e2a0 652
653 sub {
654 my ($env) = @_;
655 ...
656 }
24175cb5 657
65e03df0 658or use the C<PSGI_ENV> constant exported to retrieve it from C<@_>:
c21c9f07 659
3706e2a0 660 sub (GET + /foo + ?some_param=) {
661 my $param = $_[1];
662 my $env = $_[PSGI_ENV];
663 }
c21c9f07 664
3706e2a0 665but note that if you're trying to add a middleware, you should simply use
666Web::Simple's direct support for doing so.
c21c9f07 667
445b3ea0 668=head1 EXPORTED SUBROUTINES
c21c9f07 669
670=head2 response_filter
671
672 response_filter {
673 # Hide errors from the user because we hates them, preciousss
445b3ea0 674 if (ref($_[0]) eq 'ARRAY' && $_[0]->[0] == 500) {
675 $_[0] = [ 200, @{$_[0]}[1..$#{$_[0]}] ];
c21c9f07 676 }
445b3ea0 677 return $_[0];
c21c9f07 678 };
679
680The response_filter subroutine is designed for use inside dispatch subroutines.
681
682It creates and returns a special dispatcher that always matches, and calls
683the block passed to it as a filter on the result of running the rest of the
684current dispatch chain.
685
686Thus the filter above runs further dispatch as normal, but if the result of
687dispatch is a 500 (Internal Server Error) response, changes this to a 200 (OK)
688response without altering the headers or body.
689
690=head2 redispatch_to
691
692 redispatch_to '/other/url';
693
694The redispatch_to subroutine is designed for use inside dispatch subroutines.
695
696It creates and returns a special dispatcher that always matches, and instead
697of continuing dispatch re-delegates it to the start of the dispatch process,
698but with the path of the request altered to the supplied URL.
699
65e03df0 700Thus if you receive a POST to C</some/url> and return a redispatch to
701C</other/url>, the dispatch behaviour will be exactly as if the same POST
702request had been made to C</other/url> instead.
c21c9f07 703
3895385d 704Note, this is not the same as returning an HTTP 3xx redirect as a response;
38d5b336 705rather it is a much more efficient internal process.
3895385d 706
8c4ffad3 707=head1 CHANGES BETWEEN RELEASES
445b3ea0 708
709=head2 Changes between 0.004 and 0.005
710
711=over 4
712
713=item * dispatch {} replaced by declaring a dispatch_request method
714
715dispatch {} has gone away - instead, you write:
716
717 sub dispatch_request {
e4122532 718 my $self = shift;
445b3ea0 719 sub (GET /foo/) { ... },
720 ...
721 }
722
65e03df0 723Note that this method is still B<returning> the dispatch code - just like
724C<dispatch> did.
445b3ea0 725
65e03df0 726Also note that you need the C<< my $self = shift >> since the magic $self
e4122532 727variable went away.
728
729=item * the magic $self variable went away.
730
65e03df0 731Just add C<< my $self = shift; >> while writing your C<< sub dispatch_request { >>
e4122532 732like a normal perl method.
733
445b3ea0 734=item * subdispatch deleted - all dispatchers can now subdispatch
735
736In earlier releases you needed to write:
737
738 subdispatch sub (/foo/...) {
739 ...
740 [
741 sub (GET /bar/) { ... },
742 ...
743 ]
744 }
745
746As of 0.005, you can instead write simply:
747
748 sub (/foo/...) {
749 ...
750 (
751 sub (GET /bar/) { ... },
752 ...
753 )
754 }
8c4ffad3 755
c2150f7d 756=back
757
8c4ffad3 758=head2 Changes since Antiquated Perl
759
760=over 4
761
762=item * filter_response renamed to response_filter
763
764This is a pure rename; a global search and replace should fix it.
765
c21c9f07 766=item * dispatch [] changed to dispatch {}
8c4ffad3 767
768Simply changing
769
770 dispatch [ sub(...) { ... }, ... ];
771
772to
773
774 dispatch { sub(...) { ... }, ... };
775
776should work fine.
777
778=back
779
fb771406 780=head1 DEVELOPMENT HISTORY
781
782Web::Simple was originally written to form part of my Antiquated Perl talk for
783Italian Perl Workshop 2009, but in writing the bloggery example I realised
784that having a bare minimum system for writing web applications that doesn't
785drive me insane was rather nice and decided to spend my attempt at nanowrimo
786for 2009 improving and documenting it to the point where others could use it.
787
58fd1f7f 788The Antiquated Perl talk can be found at L<http://www.shadowcat.co.uk/archive/conference-video/> and the slides are reproduced in this distribution under
789L<Web::Simple::AntiquatedPerl>.
fb771406 790
8c4ffad3 791=head1 COMMUNITY AND SUPPORT
792
793=head2 IRC channel
794
795irc.perl.org #web-simple
796
797=head2 No mailing list yet
798
799Because mst's non-work email is a bombsite so he'd never read it anyway.
800
801=head2 Git repository
802
803Gitweb is on http://git.shadowcat.co.uk/ and the clone URL is:
804
805 git clone git://git.shadowcat.co.uk/catagits/Web-Simple.git
806
807=head1 AUTHOR
808
c2150f7d 809Matt S. Trout (mst) <mst@shadowcat.co.uk>
8c4ffad3 810
811=head1 CONTRIBUTORS
812
48904f80 813Devin Austin (dhoss) <dhoss@cpan.org>
814
815Arthur Axel 'fREW' Schmidt <frioux@gmail.com>
816
c2150f7d 817gregor herrmann (gregoa) <gregoa@debian.org>
8c4ffad3 818
48904f80 819John Napiorkowski (jnap) <jjn1056@yahoo.com>
820
821Josh McMichael <jmcmicha@linus222.gsc.wustl.edu>
822
f42be65c 823Justin Hunter (arcanez) <justin.d.hunter@gmail.com>
48904f80 824
825Kjetil Kjernsmo <kjetil@kjernsmo.net>
826
827markie <markie@nulletch64.dreamhost.com>
828
829Christian Walde (Mithaldu) <walde.christian@googlemail.com>
830
831nperez <nperez@cpan.org>
832
833Robin Edwards <robin.ge@gmail.com>
834
3c39d241 835Andrew Rodland (hobbs) <andrew@cleverdomain.org>
836
c18a76d1 837Robert Sedlacek (phaylon) <r.sedlacek@shadowcat.co.uk>
838
8c4ffad3 839=head1 COPYRIGHT
840
f42be65c 841Copyright (c) 2011 the Web::Simple L</AUTHOR> and L</CONTRIBUTORS>
8c4ffad3 842as listed above.
843
844=head1 LICENSE
845
846This library is free software and may be distributed under the same terms
847as perl itself.
848
3583ca04 849=cut