5 use warnings::illegalproto ();
7 use Web::Dispatch::Wrapper ();
9 our $VERSION = '0.011';
12 my ($class, $app_package) = @_;
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: $@";
18 warnings::illegalproto->unimport;
22 my ($class, $app_package) = @_;
25 *{"${app_package}::PSGI_ENV"} = sub () { -1 };
26 require Web::Simple::Application;
27 unshift(@{"${app_package}::ISA"}, 'Web::Simple::Application');
29 (my $name = $app_package) =~ s/::/\//g;
30 $INC{"${name}.pm"} = 'Set by "use Web::Simple;" invocation';
35 Web::Simple - A quick and easy way to build simple web applications
45 sub dispatch_request {
47 [ 200, [ 'Content-type', 'text/plain' ], [ 'Hello world!' ] ]
50 [ 405, [ 'Content-type', 'text/plain' ], [ 'Method not allowed' ] ]
54 HelloWorld->run_if_script;
56 If you save this file into your cgi-bin as C<hello-world.cgi> and then visit:
58 http://my.server.name/cgi-bin/hello-world.cgi/
60 you'll get the "Hello world!" string output to your browser. At the same time
61 this file will also act as a class module, so you can save it as HelloWorld.pm
62 and use it as-is in test scripts or other deployment mechanisms.
64 Note that you should retain the ->run_if_script even if your app is a
65 module, since this additionally makes it valid as a .psgi file, which can
66 be extremely useful during development.
68 For more complex examples and non-CGI deployment, see
69 L<Web::Simple::Deployment>. To get help with L<Web::Simple>, please connect to
70 the irc.perl.org IRC network and join #web-simple.
74 The philosophy of L<Web::Simple> is to keep to an absolute bare minimum for
75 everything. It is not designed to be used for large scale applications;
76 the L<Catalyst> web framework already works very nicely for that and is
77 a far more mature, well supported piece of software.
79 However, if you have an application that only does a couple of things, and
80 want to not have to think about complexities of deployment, then L<Web::Simple>
81 might be just the thing for you.
83 The only public interface the L<Web::Simple> module itself provides is an
86 use Web::Simple 'NameOfApplication';
88 This sets up your package (in this case "NameOfApplication" is your package)
89 so that it inherits from L<Web::Simple::Application> and imports L<strictures>,
90 as well as installs a C<PSGI_ENV> constant for convenience, as well as some
93 Importing L<strictures> will automatically make your code use the C<strict> and
94 C<warnings> pragma, so you can skip the usual:
97 use warnings FATAL => 'aa';
99 provided you 'use Web::Simple' at the top of the file. Note that we turn
100 on *fatal* warnings so if you have any warnings at any point from the file
101 that you did 'use Web::Simple' in, then your application will die. This is,
102 so far, considered a feature.
104 When we inherit from L<Web::Simple::Application> we also use L<Moo>, which is
105 the the equivalent of:
108 package NameOfApplication;
110 extends 'Web::Simple::Application';
113 So you can use L<Moo> features in your application, such as creating attributes
114 using the C<has> subroutine, etc. Please see the documentation for L<Moo> for
117 It also exports the following subroutines for use in dispatchers:
119 response_filter { ... };
121 redispatch_to '/somewhere';
125 $INC{"NameOfApplication.pm"} = 'Set by "use Web::Simple;" invocation';
127 so that perl will not attempt to load the application again even if
129 require NameOfApplication;
131 is encountered in other code.
133 =head1 DISPATCH STRATEGY
135 L<Web::Simple> despite being straightforward to use, has a powerful system
136 for matching all sorts of incoming URLs to one or more subroutines. These
137 subroutines can be simple actions to take for a given URL, or something
138 more complicated, including entire L<Plack> applications, L<Plack::Middleware>
139 and nested subdispatchers.
143 sub dispatch_request {
144 # matches: GET /user/1.htm?show_details=1
146 sub (GET + /user/* + ?show_details~ + .htm|.html|.xhtml) {
147 my ($self, $user_id, $show_details) = @_;
150 # matches: POST /user?username=frew
151 # POST /user?username=mst&first_name=matt&last_name=trout
152 sub (POST + /user + ?username=&*) {
153 my ($self, $username, $misc_params) = @_;
156 # matches: DELETE /user/1/friend/2
157 sub (DELETE + /user/*/friend/*) {
158 my ($self, $user_id, $friend_id) = @_;
161 # matches: PUT /user/1?first_name=Matt&last_name=Trout
162 sub (PUT + /user/* + ?first_name~&last_name~) {
163 my ($self, $user_id, $first_name, $last_name) = @_;
168 # matches: PUT /user/1/role/1
169 sub (PUT + /role/*) {
173 # matches: DELETE /user/1/role/1
174 sub (DELETE + /role/*) {
181 =head2 The dispatch cycle
183 At the beginning of a request, your app's dispatch_request method is called
184 with the PSGI $env as an argument. You can handle the request entirely in
185 here and return a PSGI response arrayref if you want:
187 sub dispatch_request {
188 my ($self, $env) = @_;
189 [ 404, [ 'Content-type' => 'text/plain' ], [ 'Amnesia == fail' ] ]
192 However, generally, instead of that, you return a set of dispatch subs:
194 sub dispatch_request {
196 sub (/) { redispatch_to '/index.html' },
197 sub (/user/*) { $self->show_user($_[1]) },
201 Well, a sub is a valid PSGI response too (for ultimate streaming and async
202 cleverness). If you want to return a PSGI sub you have to wrap it into an
205 sub dispatch_request {
208 # This is pure PSGI here, so read perldoc PSGI
212 If you return a subroutine with a prototype, the prototype is treated
213 as a match specification - and if the test is passed, the body of the
214 sub is called as a method any matched arguments (see below for more details).
216 You can also return a plain subroutine which will be called with just $env
217 - remember that in this case if you need $self you -must- close over it.
219 If you return a normal object, L<Web::Simple> will simply return it upwards on
220 the assumption that a response_filter (or some arbitrary L<Plack::Middleware>)
221 somewhere will convert it to something useful. This allows:
223 sub dispatch_request {
225 sub (.html) { response_filter { $self->render_zoom($_[0]) } },
226 sub (/user/*) { $self->users->get($_[1]) },
229 to render a user object to HTML, if there is an incoming URL such as:
231 http://myweb.org/user/111.html
233 This works because as we descend down the dispachers, we first match
234 C<sub (.html)>, which adds a C<response_filter> (basically a specialized routine
235 that follows the L<Plack::Middleware> specification), and then later we also
236 match C<sub (/user/*)> which gets a user and returns that as the response.
237 This user object 'bubbles up' through all the wrapping middleware until it hits
238 the C<response_filter> we defined, after which the return is converted to a
241 However, two types of object are treated specially - a Plack::App object
242 will have its C<->to_app> method called and be used as a dispatcher:
244 sub dispatch_request {
246 sub (/static/...) { Plack::App::File->new(...) },
250 A Plack::Middleware object will be used as a filter for the rest of the
251 dispatch being returned into:
253 ## responds to /admin/track_usage AND /admin/delete_accounts
255 sub dispatch_request {
258 Plack::Middleware::Session->new(%opts);
260 sub (/admin/track_usage) {
261 ## something that needs a session
263 sub (/admin/delete_accounts) {
264 ## something else that needs a session
268 Note that this is for the dispatch being -returned- to, so if you want to
269 provide it inline you need to do:
271 ## ALSO responds to /admin/track_usage AND /admin/delete_accounts
273 sub dispatch_request {
277 Plack::Middleware::Session->new(%opts);
280 ## something that needs a session
282 sub (/delete_accounts) {
283 ## something else that needs a session
288 And that's it - but remember that all this happens recursively - it's
289 dispatchers all the way down. A URL incoming pattern will run all matching
290 dispatchers and then hit all added filters or L<Plack::Middleware>.
292 =head2 Web::Simple match specifications
294 =head3 Method matches
298 A match specification beginning with a capital letter matches HTTP requests
299 with that request method.
305 A match specification beginning with a / is a path match. In the simplest
306 case it matches a specific path. To match a path with a wildcard part, you
310 $self->handle_user($_[1])
312 This will match /user/<anything> where <anything> does not include a literal
313 / character. The matched part becomes part of the match arguments. You can
314 also match more than one part:
317 my ($self, $user_1, $user_2) = @_;
319 sub (/domain/*/user/*) {
320 my ($self, $domain, $user) = @_;
322 and so on. To match an arbitrary number of parts, use -
325 my ($self, $match) = @_;
327 This will result in a single element for the entire match. Note that you can do
329 sub (/page/**/edit) {
331 to match an arbitrary number of parts up to but not including some final
338 Will match /foo/ on the beginning of the path -and- strip it. This is designed
339 to be used to construct nested dispatch structures, but can also prove useful
340 for having e.g. an optional language specification at the start of a path.
342 Note that the '...' is a "maybe something here, maybe not" so the above
343 specification will match like this:
346 /foo/ # match and strip path to '/'
347 /foo/bar/baz # match and strip path to '/bar/baz'
349 Note: Since Web::Simple handles a concept of file extensions, * and **
350 matchers will not by default match things after a final dot, and this
351 can be modified by using *.* and **.* in the final position, i.e.:
353 /one/* matches /one/two.three and captures "two"
354 /one/*.* matches /one/two.three and captures "two.three"
355 /** matches /one/two.three and captures "one/two"
356 /**.* matches /one/two.three and captures "one/two.three"
358 =head3 Extension matches
362 will match .html from the path (assuming the subroutine itself returns
363 something, of course). This is normally used for rendering - e.g.
366 response_filter { $self->render_html($_[1]) }
373 will match any extension and supplies the extension as a match argument.
375 =head3 Query and body parameter matches
377 Query and body parameters can be match via
379 sub (?<param spec>) { # match URI query
380 sub (%<param spec>) { # match body params
382 The body spec will match if the request content is either
383 application/x-www-form-urlencoded or multipart/form-data - the latter
384 of which is required for uploads, which are now handled experimentally
387 The param spec is elements of one of the following forms -
389 param~ # optional parameter
390 param= # required parameter
391 @param~ # optional multiple parameter
392 @param= # required multiple parameter
393 :param~ # optional parameter in hashref
394 :param= # required parameter in hashref
395 :@param~ # optional multiple in hashref
396 :@param= # required multiple in hashref
397 * # include all other parameters in hashref
398 @* # include all other parameters as multiple in hashref
400 separated by the & character. The arguments added to the request are
401 one per non-:/* parameter (scalar for normal, arrayref for multiple),
402 plus if any :/* specs exist a hashref containing those values.
404 Please note that if you specify a multiple type parameter match, you are
405 ensured of getting an arrayref for the value, EVEN if the current incoming
406 request has only one value. However if a parameter is specified as single
407 and multiple values are found, the last one will be used.
409 For example to match a page parameter with an optional order_by parameter one
412 sub (?page=&order_by~) {
413 my ($self, $page, $order_by) = @_;
414 return unless $page =~ /^\d+$/;
417 $_[1]->search_rs({}, $p);
421 to implement paging and ordering against a L<DBIx::Class::ResultSet> object.
423 Another Example: To get all parameters as a hashref of arrayrefs, write:
426 my ($self, $params) = @_;
429 To get two parameters as a hashref, write:
431 sub(?:user~&:domain~) {
432 my ($self, $params) = @_; # params contains only 'user' and 'domain' keys
434 You can also mix these, so:
436 sub (?foo=&@bar~&:coffee=&@*) {
437 my ($self, $foo, $bar, $params);
439 where $bar is an arrayref (possibly an empty one), and $params contains
440 arrayref values for all parameters -not- mentioned and a scalar value for
441 the 'coffee' parameter.
443 Note, in the case where you combine arrayref, single parameter and named
444 hashref style, the arrayref and single parameters will appear in C<@_> in the
445 order you defined them in the protoype, but all hashrefs will merge into a
446 single C<$params>, as in the example above.
448 =head3 Upload matches (EXPERIMENTAL)
450 Note: This feature is experimental. This means that it may not remain
451 100% in its current form. If we change it, notes on updating your code
452 will be added to the L</CHANGES BETWEEN RELEASES> section below.
454 sub (*foo=) { # param specifier can be anything valid for query or body
456 The upload match system functions exactly like a query/body match, except
457 that the values returned (if any) are C<Web::Dispatch::Upload> objects.
459 Note that this match type will succeed in two circumstances where you might
460 not expect it to - first, when the field exists but is not an upload field
461 and second, when the field exists but the form is not an upload form (i.e.
462 content type "application/x-www-form-urlencoded" rather than
463 "multipart/form-data"). In either of these cases, what you'll get back is
464 a C<Web::Dispatch::NotAnUpload> object, which will C<die> with an error
465 pointing out the problem if you try and use it. To be sure you have a real
468 $upload->is_upload # returns 1 on a valid upload, 0 on a non-upload field
470 and to get the reason why such an object is not an upload, call
472 $upload->reason # returns a reason or '' on a valid upload.
474 Other than these two methods, the upload object provides the same interface
475 as L<Plack::Request::Upload> with the addition of a stringify to the temporary
476 filename to make copying it somewhere else easier to handle.
478 =head3 Combining matches
480 Matches may be combined with the + character - e.g.
482 sub (GET + /user/*) {
484 to create an AND match. They may also be combined withe the | character - e.g.
488 to create an OR match. Matches can be nested with () - e.g.
490 sub ((GET|POST) + /user/*) {
492 and negated with ! - e.g.
494 sub (!/user/foo + /user/*) {
496 ! binds to the immediate rightmost match specification, so if you want
497 to negate a combination you will need to use
499 sub ( !(POST|PUT|DELETE) ) {
501 and | binds tighter than +, so
503 sub ((GET|POST) + /user/*) {
507 sub (GET|POST + /user/*) {
511 sub ((GET + /admin/...) | (POST + /admin/...)) {
515 sub (GET + /admin/... | POST + /admin/...) {
517 are not - the latter is equivalent to
519 sub (GET + (/admin/...|POST) + /admin/...) {
521 which will never match!
525 Note that for legibility you are permitted to use whitespace -
527 sub (GET + /user/*) {
529 but it will be ignored. This is because the perl parser strips whitespace
530 from subroutine prototypes, so this is equivalent to
534 =head3 Accessing the PSGI env hash
536 In some cases you may wish to get the raw PSGI env hash - to do this,
537 you can either use a plain sub -
544 or use the PSGI_ENV constant exported to retrieve it:
546 sub (GET + /foo + ?some_param=) {
548 my $env = $_[PSGI_ENV];
551 but note that if you're trying to add a middleware, you should simply use
552 Web::Simple's direct support for doing so.
554 =head1 EXPORTED SUBROUTINES
556 =head2 response_filter
559 # Hide errors from the user because we hates them, preciousss
560 if (ref($_[0]) eq 'ARRAY' && $_[0]->[0] == 500) {
561 $_[0] = [ 200, @{$_[0]}[1..$#{$_[0]}] ];
566 The response_filter subroutine is designed for use inside dispatch subroutines.
568 It creates and returns a special dispatcher that always matches, and calls
569 the block passed to it as a filter on the result of running the rest of the
570 current dispatch chain.
572 Thus the filter above runs further dispatch as normal, but if the result of
573 dispatch is a 500 (Internal Server Error) response, changes this to a 200 (OK)
574 response without altering the headers or body.
578 redispatch_to '/other/url';
580 The redispatch_to subroutine is designed for use inside dispatch subroutines.
582 It creates and returns a special dispatcher that always matches, and instead
583 of continuing dispatch re-delegates it to the start of the dispatch process,
584 but with the path of the request altered to the supplied URL.
586 Thus if you receive a POST to '/some/url' and return a redispatch to
587 '/other/url', the dispatch behaviour will be exactly as if the same POST
588 request had been made to '/other/url' instead.
590 Note, this is not the same as returning an HTTP 3xx redirect as a response;
591 rather it is a much more efficient internal process.
593 =head1 CHANGES BETWEEN RELEASES
595 =head2 Changes between 0.004 and 0.005
599 =item * dispatch {} replaced by declaring a dispatch_request method
601 dispatch {} has gone away - instead, you write:
603 sub dispatch_request {
605 sub (GET /foo/) { ... },
609 Note that this method is still -returning- the dispatch code - just like
612 Also note that you need the 'my $self = shift' since the magic $self
615 =item * the magic $self variable went away.
617 Just add 'my $self = shift;' while writing your 'sub dispatch_request {'
618 like a normal perl method.
620 =item * subdispatch deleted - all dispatchers can now subdispatch
622 In earlier releases you needed to write:
624 subdispatch sub (/foo/...) {
627 sub (GET /bar/) { ... },
632 As of 0.005, you can instead write simply:
637 sub (GET /bar/) { ... },
644 =head2 Changes since Antiquated Perl
648 =item * filter_response renamed to response_filter
650 This is a pure rename; a global search and replace should fix it.
652 =item * dispatch [] changed to dispatch {}
656 dispatch [ sub(...) { ... }, ... ];
660 dispatch { sub(...) { ... }, ... };
666 =head1 DEVELOPMENT HISTORY
668 Web::Simple was originally written to form part of my Antiquated Perl talk for
669 Italian Perl Workshop 2009, but in writing the bloggery example I realised
670 that having a bare minimum system for writing web applications that doesn't
671 drive me insane was rather nice and decided to spend my attempt at nanowrimo
672 for 2009 improving and documenting it to the point where others could use it.
674 The 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
675 L<Web::Simple::AntiquatedPerl>.
677 =head1 COMMUNITY AND SUPPORT
681 irc.perl.org #web-simple
683 =head2 No mailing list yet
685 Because mst's non-work email is a bombsite so he'd never read it anyway.
687 =head2 Git repository
689 Gitweb is on http://git.shadowcat.co.uk/ and the clone URL is:
691 git clone git://git.shadowcat.co.uk/catagits/Web-Simple.git
695 Matt S. Trout (mst) <mst@shadowcat.co.uk>
699 Devin Austin (dhoss) <dhoss@cpan.org>
701 Arthur Axel 'fREW' Schmidt <frioux@gmail.com>
703 gregor herrmann (gregoa) <gregoa@debian.org>
705 John Napiorkowski (jnap) <jjn1056@yahoo.com>
707 Josh McMichael <jmcmicha@linus222.gsc.wustl.edu>
709 Justin Hunter (arcanez) <justin.d.hunter@gmail.com>
711 Kjetil Kjernsmo <kjetil@kjernsmo.net>
713 markie <markie@nulletch64.dreamhost.com>
715 Christian Walde (Mithaldu) <walde.christian@googlemail.com>
717 nperez <nperez@cpan.org>
719 Robin Edwards <robin.ge@gmail.com>
723 Copyright (c) 2011 the Web::Simple L</AUTHOR> and L</CONTRIBUTORS>
728 This library is free software and may be distributed under the same terms