5 use warnings::illegalproto ();
7 use Web::Dispatch::Wrapper ();
9 our $VERSION = '0.020';
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';
37 Web::Simple - A quick and easy way to build simple web applications
47 sub dispatch_request {
49 [ 200, [ 'Content-type', 'text/plain' ], [ 'Hello world!' ] ]
52 [ 405, [ 'Content-type', 'text/plain' ], [ 'Method not allowed' ] ]
56 HelloWorld->run_if_script;
58 If you save this file into your cgi-bin as C<hello-world.cgi> and then visit:
60 http://my.server.name/cgi-bin/hello-world.cgi/
62 you'll get the "Hello world!" string output to your browser. At the same time
63 this file will also act as a class module, so you can save it as HelloWorld.pm
64 and use it as-is in test scripts or other deployment mechanisms.
66 Note that you should retain the C<< ->run_if_script >> even if your app is a
67 module, since this additionally makes it valid as a .psgi file, which can
68 be extremely useful during development.
70 For more complex examples and non-CGI deployment, see
71 L<Web::Simple::Deployment>. To get help with L<Web::Simple>, please connect to
72 the irc.perl.org IRC network and join #web-simple.
76 The philosophy of L<Web::Simple> is to keep to an absolute bare minimum for
77 everything. It is not designed to be used for large scale applications;
78 the L<Catalyst> web framework already works very nicely for that and is
79 a far more mature, well supported piece of software.
81 However, if you have an application that only does a couple of things, and
82 want to not have to think about complexities of deployment, then L<Web::Simple>
83 might be just the thing for you.
85 The only public interface the L<Web::Simple> module itself provides is an
88 use Web::Simple 'NameOfApplication';
90 This sets up your package (in this case "NameOfApplication" is your package)
91 so that it inherits from L<Web::Simple::Application> and imports L<strictures>,
92 as well as installs a C<PSGI_ENV> constant for convenience, as well as some
95 Importing L<strictures> will automatically make your code use the C<strict> and
96 C<warnings> pragma, so you can skip the usual:
99 use warnings FATAL => 'aa';
101 provided you 'use Web::Simple' at the top of the file. Note that we turn
102 on B<fatal> warnings so if you have any warnings at any point from the file
103 that you did 'use Web::Simple' in, then your application will die. This is,
104 so far, considered a feature.
106 When we inherit from L<Web::Simple::Application> we also use L<Moo>, which is
110 package NameOfApplication;
112 extends 'Web::Simple::Application';
115 So you can use L<Moo> features in your application, such as creating attributes
116 using the C<has> subroutine, etc. Please see the documentation for L<Moo> for
119 It also exports the following subroutines for use in dispatchers:
121 response_filter { ... };
123 redispatch_to '/somewhere';
127 $INC{"NameOfApplication.pm"} = 'Set by "use Web::Simple;" invocation';
129 so that perl will not attempt to load the application again even if
131 require NameOfApplication;
133 is encountered in other code.
135 One important thing to remember when using
137 NameOfApplication->run_if_script;
139 At the end of your app is that this call will create an instance of your app
140 for you automatically, regardless of context. An easier way to think of this
141 would be if the method were more verbosely named
143 NameOfApplication->run_request_if_script_else_turn_coderef_for_psgi;
145 =head1 DISPATCH STRATEGY
147 L<Web::Simple> despite being straightforward to use, has a powerful system
148 for matching all sorts of incoming URLs to one or more subroutines. These
149 subroutines can be simple actions to take for a given URL, or something
150 more complicated, including entire L<Plack> applications, L<Plack::Middleware>
151 and nested subdispatchers.
155 sub dispatch_request {
156 # matches: GET /user/1.htm?show_details=1
158 sub (GET + /user/* + ?show_details~ + .htm|.html|.xhtml) {
159 my ($self, $user_id, $show_details) = @_;
162 # matches: POST /user?username=frew
163 # POST /user?username=mst&first_name=matt&last_name=trout
164 sub (POST + /user + ?username=&*) {
165 my ($self, $username, $misc_params) = @_;
168 # matches: DELETE /user/1/friend/2
169 sub (DELETE + /user/*/friend/*) {
170 my ($self, $user_id, $friend_id) = @_;
173 # matches: PUT /user/1?first_name=Matt&last_name=Trout
174 sub (PUT + /user/* + ?first_name~&last_name~) {
175 my ($self, $user_id, $first_name, $last_name) = @_;
180 # matches: PUT /user/1/role/1
181 sub (PUT + /role/*) {
185 # matches: DELETE /user/1/role/1
186 sub (DELETE + /role/*) {
193 =head2 The dispatch cycle
195 At the beginning of a request, your app's dispatch_request method is called
196 with the PSGI $env as an argument. You can handle the request entirely in
197 here and return a PSGI response arrayref if you want:
199 sub dispatch_request {
200 my ($self, $env) = @_;
201 [ 404, [ 'Content-type' => 'text/plain' ], [ 'Amnesia == fail' ] ]
204 However, generally, instead of that, you return a set of dispatch subs:
206 sub dispatch_request {
208 sub (/) { redispatch_to '/index.html' },
209 sub (/user/*) { $self->show_user($_[1]) },
213 Well, a sub is a valid PSGI response too (for ultimate streaming and async
214 cleverness). If you want to return a PSGI sub you have to wrap it into an
217 sub dispatch_request {
220 # This is pure PSGI here, so read perldoc PSGI
224 If you return a subroutine with a prototype, the prototype is treated
225 as a match specification - and if the test is passed, the body of the
226 sub is called as a method and passed any matched arguments (see below for more details).
228 You can also return a plain subroutine which will be called with just C<$env>
229 - remember that in this case if you need C<$self> you B<must> close over it.
231 If you return a normal object, L<Web::Simple> will simply return it upwards on
232 the assumption that a response_filter (or some arbitrary L<Plack::Middleware>)
233 somewhere will convert it to something useful. This allows:
235 sub dispatch_request {
237 sub (.html) { response_filter { $self->render_zoom($_[0]) } },
238 sub (/user/*) { $self->users->get($_[1]) },
241 to render a user object to HTML, if there is an incoming URL such as:
243 http://myweb.org/user/111.html
245 This works because as we descend down the dispachers, we first match
246 C<sub (.html)>, which adds a C<response_filter> (basically a specialized routine
247 that follows the L<Plack::Middleware> specification), and then later we also
248 match C<sub (/user/*)> which gets a user and returns that as the response.
249 This user object "bubbles up" through all the wrapping middleware until it hits
250 the C<response_filter> we defined, after which the return is converted to a
253 However, two types of objects are treated specially - a L<Plack::Component> object
254 will have its C<to_app> method called and be used as a dispatcher:
256 sub dispatch_request {
258 sub (/static/...) { Plack::App::File->new(...) },
262 A L<Plack::Middleware> object will be used as a filter for the rest of the
263 dispatch being returned into:
265 ## responds to /admin/track_usage AND /admin/delete_accounts
267 sub dispatch_request {
270 Plack::Middleware::Session->new(%opts);
272 sub (/admin/track_usage) {
273 ## something that needs a session
275 sub (/admin/delete_accounts) {
276 ## something else that needs a session
280 Note that this is for the dispatch being B<returned> to, so if you want to
281 provide it inline you need to do:
283 ## ALSO responds to /admin/track_usage AND /admin/delete_accounts
285 sub dispatch_request {
289 Plack::Middleware::Session->new(%opts);
292 ## something that needs a session
294 sub (/delete_accounts) {
295 ## something else that needs a session
300 And that's it - but remember that all this happens recursively - it's
301 dispatchers all the way down. A URL incoming pattern will run all matching
302 dispatchers and then hit all added filters or L<Plack::Middleware>.
304 =head2 Web::Simple match specifications
306 Even though the following examples all use subroutine prototypes, an
307 alternative to declare a match specification for a given route is to provide a
308 L<Dancer>-like key-value list:
310 sub dispatch_request {
313 '.html' => sub { ... },
314 'GET + /user/*' => sub { ... },
316 # sub (.html) { ... },
317 # sub (GET + /user/*) { ... },
321 This can be useful in situations where you are generating a dispatch table
322 programmatically, where setting a subroutine's protoype is difficult.
324 =head3 Method matches
328 A match specification beginning with a capital letter matches HTTP requests
329 with that request method.
335 A match specification beginning with a C</> is a path match. In the simplest
336 case it matches a specific path. To match a path with a wildcard part, you
340 $self->handle_user($_[1])
342 This will match /user/<anything> where <anything> does not include a literal
343 C</> character. The matched part becomes part of the match arguments. You can
344 also match more than one part:
347 my ($self, $user_1, $user_2) = @_;
349 sub (/domain/*/user/*) {
350 my ($self, $domain, $user) = @_;
352 and so on. To match an arbitrary number of parts, use C<**>:
355 my ($self, $match) = @_;
357 This will result in a single element for the entire match. Note that you can do
359 sub (/page/**/edit) {
361 to match an arbitrary number of parts up to but not including some final
364 Note: Since Web::Simple handles a concept of file extensions, C<*> and C<**>
365 matchers will not by default match things after a final dot, and this
366 can be modified by using C<*.*> and C<**.*> in the final position, e.g.:
368 /one/* matches /one/two.three and captures "two"
369 /one/*.* matches /one/two.three and captures "two.three"
370 /** matches /one/two.three and captures "one/two"
371 /**.* matches /one/two.three and captures "one/two.three"
377 Will match C</foo/> on the beginning of the path B<and> strip it. This is
378 designed to be used to construct nested dispatch structures, but can also prove
379 useful for having e.g. an optional language specification at the start of a
382 Note that the C<...> is a "maybe something here, maybe not" so the above
383 specification will match like this:
386 /foo/ # match and strip path to '/'
387 /foo/bar/baz # match and strip path to '/bar/baz'
393 Will match on C</foo/bar/baz>, but also include C</foo>. Otherwise it
394 operates the same way as C</foo/...>.
396 /foo # match and strip path to ''
397 /foo/ # match and strip path to '/'
398 /foo/bar/baz # match and strip path to '/bar/baz'
400 Please note the difference between C<sub(/foo/...)> and C<sub(/foo...)>. In
401 the first case, this is expecting to find something after C</foo> (and fails to
402 match if nothing is found), while in the second case we can match both C</foo>
403 and C</foo/more/to/come>. The following are roughly the same:
405 sub (/foo) { 'I match /foo' },
407 sub (/bar) { 'I match /foo/bar' },
408 sub (/*) { 'I match /foo/{id}' },
414 sub (~) { 'I match /foo' },
415 sub (/bar) { 'I match /foo/bar' },
416 sub (/*) { 'I match /foo/{id}' },
419 You may prefer the latter example should you wish to take advantage of
420 subdispatchers to scope common activities. For example:
423 my $user_rs = $schema->resultset('User');
424 sub (~) { $user_rs },
425 sub (/*) { $user_rs->find($_[1]) },
428 You should note the special case path match C<sub (~)> which is only meaningful
429 when it is contained in this type of path match. It matches to an empty path.
431 =head4 Naming your patch matches
433 Any C<*>, C<**>, C<*.*>, or C<**.*> match can be followed with C<:name> to make it into a named
436 sub (/*:one/*:two/*:three/*:four) {
437 "I match /1/2/3/4 capturing { one => 1, two => 2, three => 3, four => 4 }"
440 sub (/**.*:allofit) {
441 "I match anything capturing { allofit => \$whole_path }"
444 In the specific case of a simple single-C<*> match, the C<*> may be omitted, to
447 sub (/:one/:two/:three/:four) {
448 "I match /1/2/3/4 capturing { one => 1, two => 2, three => 3, four => 4 }"
451 =head4 C</foo> and C</foo/> are different specs
453 As you may have noticed with the difference between C<sub(/foo/...)> and
454 C<sub(/foo...)>, trailing slashes in path specs are significant. This is
455 intentional and necessary to retain the ability to use relative links on
456 websites. Let's demonstrate on this link:
458 <a href="bar">bar</a>
460 If the user loads the url C</foo/> and clicks on this link, they will be
461 sent to C</foo/bar>. However when they are on the url C</foo> and click this
462 link, then they will be sent to C</bar>.
464 This makes it necessary to be explicit about the trailing slash.
466 =head3 Extension matches
470 will match .html from the path (assuming the subroutine itself returns
471 something, of course). This is normally used for rendering - e.g.:
474 response_filter { $self->render_html($_[1]) }
481 will match any extension and supplies the extension as a match argument.
483 =head3 Query and body parameter matches
485 Query and body parameters can be matched via
487 sub (?<param spec>) { # match URI query
488 sub (%<param spec>) { # match body params
490 The body spec will match if the request content is either
491 application/x-www-form-urlencoded or multipart/form-data - the latter
492 of which is required for uploads - see below.
494 The param spec is elements of one of the following forms:
496 param~ # optional parameter
497 param= # required parameter
498 @param~ # optional multiple parameter
499 @param= # required multiple parameter
500 :param~ # optional parameter in hashref
501 :param= # required parameter in hashref
502 :@param~ # optional multiple in hashref
503 :@param= # required multiple in hashref
504 * # include all other parameters in hashref
505 @* # include all other parameters as multiple in hashref
507 separated by the C<&> character. The arguments added to the request are
508 one per non-C<:>/C<*> parameter (scalar for normal, arrayref for multiple),
509 plus if any C<:>/C<*> specs exist a hashref containing those values.
511 Please note that if you specify a multiple type parameter match, you are
512 ensured of getting an arrayref for the value, EVEN if the current incoming
513 request has only one value. However if a parameter is specified as single
514 and multiple values are found, the last one will be used.
516 For example to match a C<page> parameter with an optional C<order_by> parameter one
519 sub (?page=&order_by~) {
520 my ($self, $page, $order_by) = @_;
521 return unless $page =~ /^\d+$/;
524 $_[1]->search_rs({}, $p);
528 to implement paging and ordering against a L<DBIx::Class::ResultSet> object.
530 Another example: To get all parameters as a hashref of arrayrefs, write:
533 my ($self, $params) = @_;
536 To get two parameters as a hashref, write:
538 sub(?:user~&:domain~) {
539 my ($self, $params) = @_; # params contains only 'user' and 'domain' keys
541 You can also mix these, so:
543 sub (?foo=&@bar~&:coffee=&@*) {
544 my ($self, $foo, $bar, $params);
546 where C<$bar> is an arrayref (possibly an empty one), and C<$params> contains
547 arrayref values for all parameters B<not> mentioned and a scalar value for the
550 Note, in the case where you combine arrayref, single parameter and named
551 hashref style, the arrayref and single parameters will appear in C<@_> in the
552 order you defined them in the protoype, but all hashrefs will merge into a
553 single C<$params>, as in the example above.
555 =head3 Upload matches
557 sub (*foo=) { # param specifier can be anything valid for query or body
559 The upload match system functions exactly like a query/body match, except
560 that the values returned (if any) are C<Web::Dispatch::Upload> objects.
562 Note that this match type will succeed in two circumstances where you might
563 not expect it to - first, when the field exists but is not an upload field
564 and second, when the field exists but the form is not an upload form (i.e.
565 content type C<application/x-www-form-urlencoded> rather than
566 C<multipart/form-data>). In either of these cases, what you'll get back is
567 a C<Web::Dispatch::NotAnUpload> object, which will C<die> with an error
568 pointing out the problem if you try and use it. To be sure you have a real
571 $upload->is_upload # returns 1 on a valid upload, 0 on a non-upload field
573 and to get the reason why such an object is not an upload, call
575 $upload->reason # returns a reason or '' on a valid upload.
577 Other than these two methods, the upload object provides the same interface
578 as L<Plack::Request::Upload> with the addition of a stringify to the temporary
579 filename to make copying it somewhere else easier to handle.
581 =head3 Combining matches
583 Matches may be combined with the C<+> character - e.g.
585 sub (GET + /user/*) {
587 to create an AND match. They may also be combined with the C<|> character -
592 to create an OR match. Matches can be nested with C<()> - e.g.
594 sub ((GET|POST) + /user/*) {
596 and negated with C<!> - e.g.
598 sub (!/user/foo + /user/*) {
600 C<!> binds to the immediate rightmost match specification, so if you want
601 to negate a combination you will need to use
603 sub ( !(POST|PUT|DELETE) ) {
605 and C<|> binds tighter than C<+>, so
607 sub ((GET|POST) + /user/*) {
611 sub (GET|POST + /user/*) {
615 sub ((GET + /admin/...) | (POST + /admin/...)) {
619 sub (GET + /admin/... | POST + /admin/...) {
621 are not - the latter is equivalent to
623 sub (GET + (/admin/...|POST) + /admin/...) {
625 which will never match!
629 Note that for legibility you are permitted to use whitespace:
631 sub (GET + /user/*) {
633 but it will be ignored. This is because the perl parser strips whitespace
634 from subroutine prototypes, so this is equivalent to
638 =head3 Accessing parameters via C<%_>
640 If your dispatch specification causes your dispatch subroutine to receive
641 a hash reference as its first argument, the contained named parameters
642 will be accessible via C<%_>.
644 This can be used to access your path matches, if they are named:
646 sub (GET + /foo/:path_part) {
648 ['Content-type' => 'text/plain'],
649 ["We are in $_{path_part}"],
653 Or, if your first argument would be a hash reference containing named
656 sub (GET + /foo + ?:some_param=) {
658 ['Content-type' => 'text/plain'],
659 ["We received $_{some_param} as parameter"],
663 Of course this also works when all you are doing is slurping the whole set
664 of parameters by their name:
666 sub (GET + /foo + ?*) {
668 ['Content-type' => 'text/plain'],
669 [exists($_{foo}) ? "Received a foo: $_{foo}" : "No foo!"],
673 Note that only the first hash reference will be available via C<%_>. If
674 you receive additional hash references, you will need to access them as
677 =head3 Accessing the PSGI env hash
679 In some cases you may wish to get the raw PSGI env hash - to do this,
680 you can either use a plain sub:
687 or use the C<PSGI_ENV> constant exported to retrieve it from C<@_>:
689 sub (GET + /foo + ?some_param=) {
691 my $env = $_[PSGI_ENV];
694 but note that if you're trying to add a middleware, you should simply use
695 Web::Simple's direct support for doing so.
697 =head1 EXPORTED SUBROUTINES
699 =head2 response_filter
702 # Hide errors from the user because we hates them, preciousss
703 if (ref($_[0]) eq 'ARRAY' && $_[0]->[0] == 500) {
704 $_[0] = [ 200, @{$_[0]}[1..$#{$_[0]}] ];
709 The response_filter subroutine is designed for use inside dispatch subroutines.
711 It creates and returns a special dispatcher that always matches, and calls
712 the block passed to it as a filter on the result of running the rest of the
713 current dispatch chain.
715 Thus the filter above runs further dispatch as normal, but if the result of
716 dispatch is a 500 (Internal Server Error) response, changes this to a 200 (OK)
717 response without altering the headers or body.
721 redispatch_to '/other/url';
723 The redispatch_to subroutine is designed for use inside dispatch subroutines.
725 It creates and returns a special dispatcher that always matches, and instead
726 of continuing dispatch re-delegates it to the start of the dispatch process,
727 but with the path of the request altered to the supplied URL.
729 Thus if you receive a POST to C</some/url> and return a redispatch to
730 C</other/url>, the dispatch behaviour will be exactly as if the same POST
731 request had been made to C</other/url> instead.
733 Note, this is not the same as returning an HTTP 3xx redirect as a response;
734 rather it is a much more efficient internal process.
736 =head1 CHANGES BETWEEN RELEASES
738 =head2 Changes between 0.004 and 0.005
742 =item * dispatch {} replaced by declaring a dispatch_request method
744 dispatch {} has gone away - instead, you write:
746 sub dispatch_request {
748 sub (GET /foo/) { ... },
752 Note that this method is still B<returning> the dispatch code - just like
755 Also note that you need the C<< my $self = shift >> since the magic $self
758 =item * the magic $self variable went away.
760 Just add C<< my $self = shift; >> while writing your C<< sub dispatch_request { >>
761 like a normal perl method.
763 =item * subdispatch deleted - all dispatchers can now subdispatch
765 In earlier releases you needed to write:
767 subdispatch sub (/foo/...) {
770 sub (GET /bar/) { ... },
775 As of 0.005, you can instead write simply:
780 sub (GET /bar/) { ... },
787 =head2 Changes since Antiquated Perl
791 =item * filter_response renamed to response_filter
793 This is a pure rename; a global search and replace should fix it.
795 =item * dispatch [] changed to dispatch {}
799 dispatch [ sub(...) { ... }, ... ];
803 dispatch { sub(...) { ... }, ... };
809 =head1 DEVELOPMENT HISTORY
811 Web::Simple was originally written to form part of my Antiquated Perl talk for
812 Italian Perl Workshop 2009, but in writing the bloggery example I realised
813 that having a bare minimum system for writing web applications that doesn't
814 drive me insane was rather nice and decided to spend my attempt at nanowrimo
815 for 2009 improving and documenting it to the point where others could use it.
817 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
818 L<Web::Simple::AntiquatedPerl>.
820 =head1 COMMUNITY AND SUPPORT
824 irc.perl.org #web-simple
826 =head2 No mailing list yet
828 Because mst's non-work email is a bombsite so he'd never read it anyway.
830 =head2 Git repository
832 Gitweb is on http://git.shadowcat.co.uk/ and the clone URL is:
834 git clone git://git.shadowcat.co.uk/catagits/Web-Simple.git
838 Matt S. Trout (mst) <mst@shadowcat.co.uk>
842 Devin Austin (dhoss) <dhoss@cpan.org>
844 Arthur Axel 'fREW' Schmidt <frioux@gmail.com>
846 gregor herrmann (gregoa) <gregoa@debian.org>
848 John Napiorkowski (jnap) <jjn1056@yahoo.com>
850 Josh McMichael <jmcmicha@linus222.gsc.wustl.edu>
852 Justin Hunter (arcanez) <justin.d.hunter@gmail.com>
854 Kjetil Kjernsmo <kjetil@kjernsmo.net>
856 markie <markie@nulletch64.dreamhost.com>
858 Christian Walde (Mithaldu) <walde.christian@googlemail.com>
860 nperez <nperez@cpan.org>
862 Robin Edwards <robin.ge@gmail.com>
864 Andrew Rodland (hobbs) <andrew@cleverdomain.org>
866 Robert Sedlacek (phaylon) <r.sedlacek@shadowcat.co.uk>
870 Copyright (c) 2011 the Web::Simple L</AUTHOR> and L</CONTRIBUTORS>
875 This library is free software and may be distributed under the same terms