1NAME
2
3 Dancer - lightweight yet powerful web application framework
4
5VERSION
6
7 version 1.3513
8
9SYNOPSIS
10
11 #!/usr/bin/perl
12 use Dancer;
13
14 get '/hello/:name' => sub {
15 return "Why, hello there " . param('name');
16 };
17
18 dance;
19
20 The above is a basic but functional web app created with Dancer. If you
21 want to see more examples and get up and running quickly, check out the
22 Dancer::Introduction and the Dancer::Cookbook. For examples on
23 deploying your Dancer applications, see Dancer::Deployment.
24
25DESCRIPTION
26
27 Dancer is a web application framework designed to be as effortless as
28 possible for the developer, taking care of the boring bits as easily as
29 possible, yet staying out of your way and letting you get on with
30 writing your code.
31
32 Dancer aims to provide the simplest way for writing web applications,
33 and offers the flexibility to scale between a very simple lightweight
34 web service consisting of a few lines of code in a single file, all the
35 way up to a more complex fully-fledged web application with session
36 support, templates for views and layouts, etc.
37
38 If you don't want to write CGI scripts by hand, and find Catalyst too
39 big or cumbersome for your project, Dancer is what you need.
40
41 Dancer has few pre-requisites, so your Dancer webapps will be easy to
42 deploy.
43
44 Dancer apps can be used with an embedded web server (great for easy
45 testing), and can run under PSGI/Plack for easy deployment in a variety
46 of webserver environments.
47
48MORE DOCUMENTATION
49
50 This documentation describes all the exported symbols of Dancer. If you
51 want a quick start guide to discover the framework, you should look at
52 Dancer::Introduction, or Dancer::Tutorial to learn by example.
53
54 If you want to have specific examples of code for real-life problems,
55 see the Dancer::Cookbook.
56
57 If you want to see configuration examples of different deployment
58 solutions involving Dancer and Plack, see Dancer::Deployment.
59
60 You can find out more about the many useful plugins available for
61 Dancer in Dancer::Plugins.
62
63DANCER 2
64
65 This is the original version of Dancer, which is now in maintenance
66 mode. This means that it will not receive significant new features, but
67 will continue to receive bugfixes and security fixes. However, no "end
68 of life" date has been set, and it is expected that this version of
69 Dancer will continue to receive bugfixes and security fixes for quite
70 some time yet.
71
72 However, you should consider migrating to Dancer2 instead when you can,
73 and are advised to use Dancer2 for newly-started apps.
74
75 Dancer2 is mostly backwards compatible, but has been re-written from
76 the ground up to be more maintainable and extensible, and is the future
77 of Dancer.
78
79 Dancer2::Manual::Migration covers the changes you should be aware of
80 when migrating an existing Dancer 1 powered app to Dancer 2.
81
82EXPORTS
83
84 By default, use Dancer exports all the functions below plus sets up
85 your app. You can control the exporting through the normal Exporter
86 mechanism. For example:
87
88 # Just export the route controllers
89 use Dancer qw(get post put patch del);
90
91 # Export everything but pass to avoid clashing with Test::More
92 use Test::More;
93 use Dancer qw(!pass);
94
95 Please note that the utf8 and strict pragmas are exported by this
96 module.
97
98 By default, the warnings pragma will also be exported, meaning your
99 app/script will be running under use warnings. If you do not want this,
100 set the global_warnings setting to a false value.
101
102 There are also some special tags to control exports and behaviour.
103
104 :moose
105
106 This will export everything except functions which clash with Moose.
107 Currently these are after and before.
108
109 :syntax
110
111 This tells Dancer to just export symbols and not set up your app. This
112 is most useful for writing Dancer code outside of your main route
113 handler.
114
115 :tests
116
117 This will export everything except functions which clash with commonly
118 used testing modules. Currently these are pass.
119
120 It can be combined with other export pragmas. For example, while
121 testing...
122
123 use Test::More;
124 use Dancer qw(:syntax :tests);
125
126 # Test::Most also exports "set" and "any"
127 use Test::Most;
128 use Dancer qw(:syntax :tests !set !any);
129
130 # Alternatively, if you want to use Dancer's set and any...
131 use Test::Most qw(!set !any);
132 use Dancer qw(:syntax :tests);
133
134 :script
135
136 This will export all the keywords, load the configuration, and will not
137 try to parse command-line arguments via Dancer::GetOpt.
138
139 This is useful when you want to use your Dancer application from a
140 script.
141
142 use MyApp;
143 use Dancer ':script';
144 MyApp::schema('DBSchema')->deploy();
145
146 Note that using :script will disable command-line parsing for all
147 subsequent invocations of use Dancer (such that you don't have to use
148 :script for each and every module to make sure the command-line
149 arguments don't get stolen by Dancer).
150
151 !keyword
152
153 If you want to simply prevent Dancer from exporting specific keywords
154 (perhaps you plan to implement them yourself in a different way, or you
155 don't plan to use them and they clash with another module you're
156 loading), you can simply exclude them:
157
158 use Dancer qw(!session);
159
160 The above would import all keywords as normal, with the exception of
161 session.
162
163FUNCTIONS
164
165 after
166
167 Deprecated - see the after hook.
168
169 any
170
171 Defines a route for multiple HTTP methods at once:
172
173 any ['get', 'post'] => '/myaction' => sub {
174 # code
175 };
176
177 Or even, a route handler that would match any HTTP methods:
178
179 any '/myaction' => sub {
180 # code
181 };
182
183 before
184
185 Deprecated - see the before hook.
186
187 before_template
188
189 Deprecated - see the before_template hook.
190
191 cookies
192
193 Accesses cookies values, it returns a HashRef of Dancer::Cookie
194 objects:
195
196 get '/some_action' => sub {
197 my $cookie = cookies->{name};
198 return $cookie->value;
199 };
200
201 In the case you have stored something other than a Scalar in your
202 cookie:
203
204 get '/some_action' => sub {
205 my $cookie = cookies->{oauth};
206 my %values = $cookie->value;
207 return ($values{token}, $values{token_secret});
208 };
209
210 cookie
211
212 Accesses a cookie value (or sets it). Note that this method will
213 eventually be preferred over set_cookie.
214
215 cookie lang => "fr-FR"; # set a cookie and return its value
216 cookie lang => "fr-FR", expires => "2 hours"; # extra cookie info
217 cookie "lang" # return a cookie value
218
219 If your cookie value is a key/value URI string, like
220
221 token=ABC&user=foo
222
223 cookie will only return the first part (token=ABC) if called in scalar
224 context. Use list context to fetch them all:
225
226 my @values = cookie "name";
227
228 Note that if the client has sent more than one cookie with the same
229 value, the one returned will be the last one seen. This should only
230 happen if you have set multiple cookies with the same name but
231 different paths. So, don't do that.
232
233 config
234
235 Accesses the configuration of the application:
236
237 get '/appname' => sub {
238 return "This is " . config->{appname};
239 };
240
241 content_type
242
243 Sets the content-type rendered, for the current route handler:
244
245 get '/cat/:txtfile' => sub {
246 content_type 'text/plain';
247
248 # here we can dump the contents of param('txtfile')
249 };
250
251 You can use abbreviations for content types. For instance:
252
253 get '/svg/:id' => sub {
254 content_type 'svg';
255
256 # here we can dump the image with id param('id')
257 };
258
259 Note that if you want to change the default content-type for every
260 route, you have to change the content_type setting instead.
261
262 dance
263
264 Alias for the start keyword.
265
266 dancer_version
267
268 Returns the version of Dancer. If you need the major version, do
269 something like:
270
271 int(dancer_version);
272
273 debug
274
275 Logs a message of debug level:
276
277 debug "This is a debug message";
278
279 See Dancer::Logger for details on how to configure where log messages
280 go.
281
282 dirname
283
284 Returns the dirname of the path given:
285
286 my $dir = dirname($some_path);
287
288 engine
289
290 Given a namespace, returns the current engine object
291
292 my $template_engine = engine 'template';
293 my $html = $template_engine->apply_renderer(...);
294 $template_engine->apply_layout($html);
295
296 error
297
298 Logs a message of error level:
299
300 error "This is an error message";
301
302 See Dancer::Logger for details on how to configure where log messages
303 go.
304
305 false
306
307 Constant that returns a false value (0).
308
309 forward
310
311 Runs an internal redirect of the current request to another request.
312 This helps you avoid having to redirect the user using HTTP and set
313 another request to your application.
314
315 It effectively lets you chain routes together in a clean manner.
316
317 get '/demo/articles/:article_id' => sub {
318
319 # you'll have to implement this next sub yourself :)
320 change_the_main_database_to_demo();
321
322 forward "/articles/" . params->{article_id};
323 };
324
325 In the above example, the users that reach /demo/articles/30 will
326 actually reach /articles/30 but we've changed the database to demo
327 before.
328
329 This is pretty cool because it lets us retain our paths and offer a
330 demo database by merely going to /demo/....
331
332 You'll notice that in the example we didn't indicate whether it was GET
333 or POST. That is because forward chains the same type of route the user
334 reached. If it was a GET, it will remain a GET (but if you do need to
335 change the method, you can do so; read on below for details.)
336
337 WARNING : using forward will not preserve session data set on the
338 forwarding rule.
339
340 WARNING : Issuing a forward immediately exits the current route, and
341 perform the forward. Thus, any code after a forward is ignored, until
342 the end of the route. e.g.
343
344 get '/foo/:article_id' => sub {
345 if ($condition) {
346 forward "/articles/" . params->{article_id};
347 # The following code is never executed
348 do_stuff();
349 }
350
351 more_stuff();
352 };
353
354 So it's not necessary anymore to use return with forward.
355
356 Note that forward doesn't parse GET arguments. So, you can't use
357 something like:
358
359 return forward '/home?authorized=1';
360
361 But forward supports an optional HashRef with parameters to be added to
362 the actual parameters:
363
364 return forward '/home', { authorized => 1 };
365
366 Finally, you can add some more options to the forward method, in a
367 third argument, also as a HashRef. That option is currently only used
368 to change the method of your request. Use with caution.
369
370 return forward '/home', { auth => 1 }, { method => 'POST' };
371
372 from_dumper ($structure)
373
374 Deserializes a Data::Dumper structure.
375
376 from_json ($structure, \%options)
377
378 Deserializes a JSON structure. Can receive optional arguments. Those
379 arguments are valid JSON arguments to change the behaviour of the
380 default JSON::from_json function.
381
382 Compatibility notice: from_json changed in 1.3002 to take a hashref as
383 options, instead of a hash.
384
385 from_yaml ($structure)
386
387 Deserializes a YAML structure.
388
389 from_xml ($structure, %options)
390
391 Deserializes a XML structure. Can receive optional arguments. These
392 arguments are valid XML::Simple arguments to change the behaviour of
393 the default XML::Simple::XMLin function.
394
395 get
396
397 Defines a route for HTTP GET requests to the given path:
398
399 get '/' => sub {
400 return "Hello world";
401 }
402
403 Note that a route to match HEAD requests is automatically created as
404 well.
405
406 halt
407
408 Sets a response object with the content given.
409
410 When used as a return value from a filter, this breaks the execution
411 flow and renders the response immediately:
412
413 hook before sub {
414 if ($some_condition) {
415 halt("Unauthorized");
416 # This code is not executed :
417 do_stuff();
418 }
419 };
420
421 get '/' => sub {
422 "hello there";
423 };
424
425 WARNING : Issuing a halt immediately exits the current route, and
426 perform the halt. Thus, any code after a halt is ignored, until the end
427 of the route. So it's not necessary anymore to use return with halt.
428
429 headers
430
431 Adds custom headers to responses:
432
433 get '/send/headers', sub {
434 headers 'X-Foo' => 'bar', X-Bar => 'foo';
435 }
436
437 header
438
439 adds a custom header to response:
440
441 get '/send/header', sub {
442 header 'x-my-header' => 'shazam!';
443 }
444
445 Note that it will overwrite the old value of the header, if any. To
446 avoid that, see "push_header".
447
448 push_header
449
450 Do the same as header, but allow for multiple headers with the same
451 name.
452
453 get '/send/header', sub {
454 push_header 'x-my-header' => '1';
455 push_header 'x-my-header' => '2';
456 will result in two headers "x-my-header" in the response
457 }
458
459 hook
460
461 Adds a hook at some position. For example :
462
463 hook before_serializer => sub {
464 my $response = shift;
465 $response->content->{generated_at} = localtime();
466 };
467
468 There can be multiple hooks assigned to a given position, and each will
469 be executed in order. Note that all hooks are always called, even if
470 they are defined in a different package loaded via load_app.
471
472 (For details on how to register new hooks from within plugins, see
473 Dancer::Hook.) Supported before hooks (in order of execution):
474
475 before_deserializer
476
477 This hook receives no arguments.
478
479 hook before_deserializer => sub {
480 ...
481 };
482
483 before_file_render
484
485 This hook receives as argument the path of the file to render.
486
487 hook before_file_render => sub {
488 my $path = shift;
489 ...
490 };
491
492 before_error_init
493
494 This hook receives as argument a Dancer::Error object.
495
496 hook before_error_init => sub {
497 my $error = shift;
498 ...
499 };
500
501 before_error_render
502
503 This hook receives as argument a Dancer::Error object.
504
505 hook before_error_render => sub {
506 my $error = shift;
507 };
508
509 before
510
511 This hook receives one argument, the route being executed (a
512 Dancer::Route object).
513
514 hook before => sub {
515 my $route_handler = shift;
516 ...
517 };
518
519 it is equivalent to the deprecated
520
521 before sub {
522 ...
523 };
524
525 before_template_render
526
527 This is an alias to 'before_template'.
528
529 This hook receives as argument a HashRef containing the tokens that
530 will be passed to the template. You can use it to add more tokens, or
531 delete some specific token.
532
533 hook before_template_render => sub {
534 my $tokens = shift;
535 delete $tokens->{user};
536 $tokens->{time} = localtime;
537 };
538
539 is equivalent to
540
541 hook before_template => sub {
542 my $tokens = shift;
543 delete $tokens->{user};
544 $tokens->{time} = localtime;
545 };
546
547 before_layout_render
548
549 This hook receives two arguments. The first one is a HashRef
550 containing the tokens. The second is a ScalarRef representing the
551 content of the template.
552
553 hook before_layout_render => sub {
554 my ($tokens, $html_ref) = @_;
555 ...
556 };
557
558 before_serializer
559
560 This hook receives as argument a Dancer::Response object.
561
562 hook before_serializer => sub {
563 my $response = shift;
564 $response->content->{start_time} = time();
565 };
566
567 Supported after hooks (in order of execution):
568
569 after_deserializer
570
571 This hook receives no arguments.
572
573 hook after_deserializer => sub {
574 ...
575 };
576
577 after_file_render
578
579 This hook receives as argument a Dancer::Response object.
580
581 hook after_file_render => sub {
582 my $response = shift;
583 };
584
585 after_template_render
586
587 This hook receives as argument a ScalarRef representing the content
588 generated by the template.
589
590 hook after_template_render => sub {
591 my $html_ref = shift;
592 };
593
594 after_layout_render
595
596 This hook receives as argument a ScalarRef representing the content
597 generated by the layout
598
599 hook after_layout_render => sub {
600 my $html_ref = shift;
601 };
602
603 after
604
605 This is an alias for after.
606
607 This hook runs after a request has been processed, but before the
608 response is sent.
609
610 It receives a Dancer::Response object, which it can modify if it
611 needs to make changes to the response which is about to be sent.
612
613 hook after => sub {
614 my $response = shift;
615 };
616
617 This is equivalent to the deprecated
618
619 after sub {
620 my $response = shift;
621 };
622
623 after_error_render
624
625 This hook receives as argument a Dancer::Response object.
626
627 hook after_error_render => sub {
628 my $response = shift;
629 };
630
631 on_handler_exception
632
633 This hook is called when an exception has been caught, at the handler
634 level, just before creating and rendering Dancer::Error. This hook
635 receives as argument a Dancer::Exception object.
636
637 hook on_handler_exception => sub {
638 my $exception = shift;
639 };
640
641 on_reset_state
642
643 This hook is called when global state is reset to process a new
644 request. It receives a boolean value that indicates whether the reset
645 was called as part of a forwarded request.
646
647 hook on_reset_state => sub {
648 my $is_forward = shift;
649 };
650
651 on_route_exception
652
653 This hook is called when an exception has been caught, at the route
654 level, just before rethrowing it higher. This hook receives the
655 exception as argument. It can be a Dancer::Exception, or a string, or
656 whatever was used to die.
657
658 hook on_route_exception => sub {
659 my $exception = shift;
660 };
661
662 info
663
664 Logs a message of info level:
665
666 info "This is a info message";
667
668 See Dancer::Logger for details on how to configure where log messages
669 go.
670
671 layout
672
673 This method is deprecated. Use set:
674
675 set layout => 'user';
676
677 logger
678
679 Deprecated. Use <set logger => 'console'> to change current logger
680 engine.
681
682 load
683
684 Loads one or more perl scripts in the current application's namespace.
685 Syntactic sugar around Perl's require:
686
687 load 'UserActions.pl', 'AdminActions.pl';
688
689 load_app
690
691 Loads a Dancer package. This method sets the libdir to the current
692 ./lib directory:
693
694 # if we have lib/Webapp.pm, we can load it like:
695 load_app 'Webapp';
696 # or with options
697 load_app 'Forum', prefix => '/forum', settings => {foo => 'bar'};
698
699 Note that the package loaded using load_app must import Dancer with the
700 :syntax option.
701
702 To load multiple apps repeat load_app:
703
704 load_app 'one';
705 load_app 'two';
706
707 The old way of loading multiple apps in one go (load_app 'one', 'two';)
708 is deprecated.
709
710 mime
711
712 Shortcut to access the instance object of Dancer::MIME. You should read
713 the Dancer::MIME documentation for full details, but the most
714 commonly-used methods are summarized below:
715
716 # set a new mime type
717 mime->add_type( foo => 'text/foo' );
718
719 # set a mime type alias
720 mime->add_alias( f => 'foo' );
721
722 # get mime type for an alias
723 my $m = mime->for_name( 'f' );
724
725 # get mime type for a file (based on extension)
726 my $m = mime->for_file( "foo.bar" );
727
728 # get current defined default mime type
729 my $d = mime->default;
730
731 # set the default mime type using config.yml
732 # or using the set keyword
733 set default_mime_type => 'text/plain';
734
735 params
736
737 This method should be called from a route handler. It's an alias for
738 the Dancer::Request params accessor. In list context it returns a list
739 of key/value pair of all defined parameters. In scalar context it
740 returns a hash reference instead. Check param below to access quickly
741 to a single parameter value.
742
743 param
744
745 This method should be called from a route handler. This method is an
746 accessor to the parameters hash table.
747
748 post '/login' => sub {
749 my $username = param "user";
750 my $password = param "pass";
751 # ...
752 }
753
754 param_array
755
756 This method should be called from a route handler. Like param, but
757 always returns the parameter value or values as a list. Returns the
758 number of values in scalar context.
759
760 # if request is '/tickets?tag=open&tag=closed&order=desc'...
761 get '/tickets' => sub {
762 my @tags = param_array 'tag'; # ( 'open', 'closed' )
763 my $tags = param 'tag'; # array ref
764
765 my @order = param_array 'order'; # ( 'desc' )
766 my $order = param 'order'; # 'desc'
767 };
768
769 pass
770
771 This method should be called from a route handler. Tells Dancer to pass
772 the processing of the request to the next matching route.
773
774 WARNING : Issuing a pass immediately exits the current route, and
775 performs the pass. Thus, any code after a pass is ignored until the end
776 of the route. So it's not necessary any more to use return with pass.
777
778 get '/some/route' => sub {
779 if (...) {
780 # we want to let the next matching route handler process this one
781 pass(...);
782 # This code will be ignored
783 do_stuff();
784 }
785 };
786
787 patch
788
789 Defines a route for HTTP PATCH requests to the given URL:
790
791 patch '/resource' => sub { ... };
792
793 (PATCH is a relatively new and not-yet-common HTTP verb, which is
794 intended to work as a "partial-PUT", transferring just the changes;
795 please see http://tools.ietf.org/html/rfc5789|RFC5789 for further
796 details.)
797
798 Please be aware that, if you run your app in standalone mode, PATCH
799 requests will not reach your app unless you have a new version of
800 HTTP::Server::Simple which accepts PATCH as a valid verb. The current
801 version at time of writing, 0.44, does not. A pull request has been
802 submitted to add this support, which you can find at:
803
804 https://github.com/bestpractical/http-server-simple/pull/1
805
806 path
807
808 Concatenates multiple paths together, without worrying about the
809 underlying operating system:
810
811 my $path = path(dirname($0), 'lib', 'File.pm');
812
813 It also normalizes (cleans) the path aesthetically. It does not verify
814 the path exists.
815
816 post
817
818 Defines a route for HTTP POST requests to the given URL:
819
820 post '/' => sub {
821 return "Hello world";
822 }
823
824 prefix
825
826 Defines a prefix for each route handler, like this:
827
828 prefix '/home';
829
830 From here, any route handler is defined to /home/*:
831
832 get '/page1' => sub {}; # will match '/home/page1'
833
834 You can unset the prefix value:
835
836 prefix undef;
837 get '/page1' => sub {}; will match /page1
838
839 For a safer alternative you can use lexical prefix like this:
840
841 prefix '/home' => sub {
842 ## Prefix is set to '/home' here
843
844 get ...;
845 get ...;
846 };
847 ## prefix reset to the previous version here
848
849 This makes it possible to nest prefixes:
850
851 prefix '/home' => sub {
852 ## some routes
853
854 prefix '/private' => sub {
855 ## here we are under /home/private...
856
857 ## some more routes
858 };
859 ## back to /home
860 };
861 ## back to the root
862
863 Notice: once you have a prefix set, do not add a caret to the regex:
864
865 prefix '/foo';
866 get qr{^/bar} => sub { ... } # BAD BAD BAD
867 get qr{/bar} => sub { ... } # Good!
868
869 del
870
871 Defines a route for HTTP DELETE requests to the given URL:
872
873 del '/resource' => sub { ... };
874
875 options
876
877 Defines a route for HTTP OPTIONS requests to the given URL:
878
879 options '/resource' => sub { ... };
880
881 put
882
883 Defines a route for HTTP PUT requests to the given URL:
884
885 put '/resource' => sub { ... };
886
887 redirect
888
889 Generates an HTTP redirect (302). You can either redirect to a
890 completely different site or within the application:
891
892 get '/twitter', sub {
893 redirect 'http://twitter.com/me';
894 };
895
896 You can also force Dancer to return a specific 300-ish HTTP response
897 code:
898
899 get '/old/:resource', sub {
900 redirect '/new/'.params->{resource}, 301;
901 };
902
903 It is important to note that issuing a redirect by itself does not exit
904 and redirect immediately. Redirection is deferred until after the
905 current route or filter has been processed. To exit and redirect
906 immediately, use the return function, e.g.
907
908 get '/restricted', sub {
909 return redirect '/login' if accessDenied();
910 return 'Welcome to the restricted section';
911 };
912
913 render_with_layout
914
915 Allows a handler to provide plain HTML (or other content), but have it
916 rendered within the layout still.
917
918 This method is DEPRECATED, and will be removed soon. Instead, you
919 should be using the engine keyword:
920
921 get '/foo' => sub {
922 # Do something which generates HTML directly (maybe using
923 # HTML::Table::FromDatabase or something)
924 my $content = ...;
925
926 # get the template engine
927 my $template_engine = engine 'template';
928
929 # apply the layout (not the renderer), and return the result
930 $template_engine->apply_layout($content)
931 };
932
933 It works very similarly to template in that you can pass tokens to be
934 used in the layout, and/or options to control the way the layout is
935 rendered. For instance, to use a custom layout:
936
937 render_with_layout $content, {}, { layout => 'layoutname' };
938
939 request
940
941 Returns a Dancer::Request object representing the current request.
942
943 See the Dancer::Request documentation for the methods you can call, for
944 example:
945
946 request->referer; # value of the HTTP referer header
947 request->remote_address; # user's IP address
948 request->user_agent; # User-Agent header value
949
950 send_error
951
952 Returns an HTTP error. By default the HTTP code returned is 500:
953
954 get '/photo/:id' => sub {
955 if (...) {
956 send_error("Not allowed", 403);
957 } else {
958 # return content
959 }
960 }
961
962 WARNING : Issuing a send_error immediately exits the current route, and
963 perform the send_error. Thus, any code after a send_error is ignored,
964 until the end of the route. So it's not necessary anymore to use return
965 with send_error.
966
967 get '/some/route' => sub {
968 if (...) {
969 # we want to let the next matching route handler process this one
970 send_error(..);
971 # This code will be ignored
972 do_stuff();
973 }
974 };
975
976 send_file
977
978 Lets the current route handler send a file to the client. Note that the
979 path of the file must be relative to the public directory unless you
980 use the system_path option (see below).
981
982 get '/download/:file' => sub {
983 send_file(params->{file});
984 }
985
986 WARNING : Issuing a send_file immediately exits the current route, and
987 performs the send_file. Thus, any code after a send_file is ignored
988 until the end of the route. So it's not necessary any more to use
989 return with send_file.
990
991 get '/some/route' => sub {
992 if (...) {
993 # we want to let the next matching route handler process this one
994 send_file(...);
995 # This code will be ignored
996 do_stuff();
997 }
998 };
999
1000 Send file supports streaming possibility using PSGI streaming. The
1001 server should support it but normal streaming is supported on most, if
1002 not all.
1003
1004 get '/download/:file' => sub {
1005 send_file( params->{file}, streaming => 1 );
1006 }
1007
1008 You can control what happens using callbacks.
1009
1010 First, around_content allows you to get the writer object and the chunk
1011 of content read, and then decide what to do with each chunk:
1012
1013 get '/download/:file' => sub {
1014 send_file(
1015 params->{file},
1016 streaming => 1,
1017 callbacks => {
1018 around_content => sub {
1019 my ( $writer, $chunk ) = @_;
1020 $writer->write("* $chunk");
1021 },
1022 },
1023 );
1024 }
1025
1026 You can use around to all get all the content (whether a filehandle if
1027 it's a regular file or a full string if it's a scalar ref) and decide
1028 what to do with it:
1029
1030 get '/download/:file' => sub {
1031 send_file(
1032 params->{file},
1033 streaming => 1,
1034 callbacks => {
1035 around => sub {
1036 my ( $writer, $content ) = @_;
1037
1038 # we know it's a text file, so we'll just stream
1039 # line by line
1040 while ( my $line = <$content> ) {
1041 $writer->write($line);
1042 }
1043 },
1044 },
1045 );
1046 }
1047
1048 Or you could use override to control the entire streaming callback
1049 request:
1050
1051 get '/download/:file' => sub {
1052 send_file(
1053 params->{file},
1054 streaming => 1,
1055 callbacks => {
1056 override => sub {
1057 my ( $respond, $response ) = @_;
1058
1059 my $writer = $respond->( [ $newstatus, $newheaders ] );
1060 $writer->write("some line");
1061 },
1062 },
1063 );
1064 }
1065
1066 You can also set the number of bytes that will be read at a time
1067 (default being 42K bytes) using bytes:
1068
1069 get '/download/:file' => sub {
1070 send_file(
1071 params->{file},
1072 streaming => 1,
1073 bytes => 524288, # 512K
1074 );
1075 };
1076
1077 The content-type will be set depending on the current MIME types
1078 definition (see mime if you want to define your own).
1079
1080 If your filename does not have an extension, or you need to force a
1081 specific mime type, you can pass it to send_file as follows:
1082
1083 send_file(params->{file}, content_type => 'image/png');
1084
1085 Also, you can use your aliases or file extension names on content_type,
1086 like this:
1087
1088 send_file(params->{file}, content_type => 'png');
1089
1090 For files outside your public folder, you can use the system_path
1091 switch. Just bear in mind that its use needs caution as it can be
1092 dangerous.
1093
1094 send_file('/etc/passwd', system_path => 1);
1095
1096 If you have your data in a scalar variable, send_file can be useful as
1097 well. Pass a reference to that scalar, and send_file will behave as if
1098 there were a file with that contents:
1099
1100 send_file( \$data, content_type => 'image/png' );
1101
1102 Note that Dancer is unable to guess the content type from the data
1103 contents. Therefore you might need to set the content_type properly.
1104 For this kind of usage an attribute named filename can be useful. It is
1105 used as the Content-Disposition header, to hint the browser about the
1106 filename it should use.
1107
1108 send_file( \$data, content_type => 'image/png'
1109 filename => 'onion.png' );
1110
1111 set
1112
1113 Defines a setting:
1114
1115 set something => 'value';
1116
1117 You can set more than one value at once:
1118
1119 set something => 'value', otherthing => 'othervalue';
1120
1121 setting
1122
1123 Returns the value of a given setting:
1124
1125 setting('something'); # 'value'
1126
1127 set_cookie
1128
1129 Creates or updates cookie values:
1130
1131 get '/some_action' => sub {
1132 set_cookie name => 'value',
1133 expires => (time + 3600),
1134 domain => '.foo.com';
1135 };
1136
1137 In the example above, only 'name' and 'value' are mandatory.
1138
1139 You can also store more complex structure in your cookies:
1140
1141 get '/some_auth' => sub {
1142 set_cookie oauth => {
1143 token => $twitter->request_token,
1144 token_secret => $twitter->secret_token,
1145 ...
1146 };
1147 };
1148
1149 You can't store more complex structure than this. All keys in the
1150 HashRef should be Scalars; storing references will not work.
1151
1152 See Dancer::Cookie for further options when creating your cookie.
1153
1154 Note that this method will be eventually deprecated in favor of the new
1155 cookie method.
1156
1157 session
1158
1159 Provides access to all data stored in the user's session (if any).
1160
1161 It can also be used as a setter to store data in the session:
1162
1163 # getter example
1164 get '/user' => sub {
1165 if (session('user')) {
1166 return "Hello, ".session('user')->name;
1167 }
1168 };
1169
1170 # setter example
1171 post '/user/login' => sub {
1172 ...
1173 if ($logged_in) {
1174 session user => $user;
1175 }
1176 ...
1177 };
1178
1179 You may also need to clear a session:
1180
1181 # destroy session
1182 get '/logout' => sub {
1183 ...
1184 session->destroy;
1185 ...
1186 };
1187
1188 If you need to fetch the session ID being used for any reason:
1189
1190 my $id = session->id;
1191
1192 In order to be able to use sessions, first you need to enable session
1193 support in one of the configuration files. A quick way to do it is to
1194 add
1195
1196 session: "YAML"
1197
1198 to config.yml.
1199
1200 For more details, see Dancer::Session.
1201
1202 splat
1203
1204 Returns the list of captures made from a route handler with a route
1205 pattern which includes wildcards:
1206
1207 get '/file/*.*' => sub {
1208 my ($file, $extension) = splat;
1209 ...
1210 };
1211
1212 There is also the extensive splat (A.K.A. "megasplat"), which allows
1213 extensive greedier matching, available using two asterisks. The
1214 additional path is broken down and returned as an ArrayRef:
1215
1216 get '/entry/*/tags/**' => sub {
1217 my ( $entry_id, $tags ) = splat;
1218 my @tags = @{$tags};
1219 };
1220
1221 This helps with chained actions:
1222
1223 get '/team/*/**' => sub {
1224 my ($team) = splat;
1225 var team => $team;
1226 pass;
1227 };
1228
1229 prefix '/team/*';
1230
1231 get '/player/*' => sub {
1232 my ($player) = splat;
1233
1234 # etc...
1235 };
1236
1237 get '/score' => sub {
1238 return score_for( vars->{'team'} );
1239 };
1240
1241 start
1242
1243 Starts the application or the standalone server (depending on the
1244 deployment choices).
1245
1246 This keyword should be called at the very end of the script, once all
1247 routes are defined. At this point, Dancer takes over control.
1248
1249 status
1250
1251 Changes the status code provided by an action. By default, an action
1252 will produce an HTTP 200 OK status code, meaning everything is OK:
1253
1254 get '/download/:file' => {
1255 if (! -f params->{file}) {
1256 status 'not_found';
1257 return "File does not exist, unable to download";
1258 }
1259 # serving the file...
1260 };
1261
1262 In that example Dancer will notice that the status has changed, and
1263 will render the response accordingly.
1264
1265 The status keyword receives either a numeric status code or its name in
1266 lower case, with underscores as a separator for blanks. See the list in
1267 "HTTP CODES" in Dancer::HTTP.
1268
1269 template
1270
1271 Returns the response of processing the given template with the given
1272 parameters (and optional settings), wrapping it in the default or
1273 specified layout too, if layouts are in use.
1274
1275 An example of a route handler which returns the result of using
1276 template to build a response with the current template engine:
1277
1278 get '/' => sub {
1279 ...
1280 return template 'some_view', { token => 'value'};
1281 };
1282
1283 Note that template simply returns the content, so when you use it in a
1284 route handler, if execution of the route handler should stop at that
1285 point, make sure you use 'return' to ensure your route handler returns
1286 the content.
1287
1288 Since template just returns the result of rendering the template, you
1289 can also use it to perform other templating tasks, e.g. generating
1290 emails:
1291
1292 post '/some/route' => sub {
1293 if (...) {
1294 email {
1295 to => 'someone@example.com',
1296 from => 'foo@example.com',
1297 subject => 'Hello there',
1298 msg => template('emails/foo', { name => params->{name} }),
1299 };
1300
1301 return template 'message_sent';
1302 } else {
1303 return template 'error';
1304 }
1305 };
1306
1307 Compatibility notice: template was changed in version 1.3090 to
1308 immediately interrupt execution of a route handler and return the
1309 content, as it's typically used at the end of a route handler to return
1310 content. However, this caused issues for some people who were using
1311 template to generate emails etc, rather than accessing the template
1312 engine directly, so this change has been reverted in 1.3091.
1313
1314 The first parameter should be a template available in the views
1315 directory, the second one (optional) is a HashRef of tokens to
1316 interpolate, and the third (again optional) is a HashRef of options.
1317
1318 For example, to disable the layout for a specific request:
1319
1320 get '/' => sub {
1321 template 'index', {}, { layout => undef };
1322 };
1323
1324 Or to request a specific layout, of course:
1325
1326 get '/user' => sub {
1327 template 'user', {}, { layout => 'user' };
1328 };
1329
1330 Some tokens are automatically added to your template (perl_version,
1331 dancer_version, settings, request, params, vars and, if you have
1332 sessions enabled, session). Check Dancer::Template::Abstract for
1333 further details.
1334
1335 to_dumper ($structure)
1336
1337 Serializes a structure with Data::Dumper.
1338
1339 to_json ($structure, \%options)
1340
1341 Serializes a structure to JSON. Can receive optional arguments. Thoses
1342 arguments are valid JSON arguments to change the behaviour of the
1343 default JSON::to_json function.
1344
1345 Compatibility notice: to_json changed in 1.3002 to take a hashref as
1346 options, instead of a hash.
1347
1348 to_yaml ($structure)
1349
1350 Serializes a structure to YAML.
1351
1352 to_xml ($structure, %options)
1353
1354 Serializes a structure to XML. Can receive optional arguments. Thoses
1355 arguments are valid XML::Simple arguments to change the behaviour of
1356 the default XML::Simple::XMLout function.
1357
1358 true
1359
1360 Constant that returns a true value (1).
1361
1362 upload
1363
1364 Provides access to file uploads. Any uploaded file is accessible as a
1365 Dancer::Request::Upload object. You can access all parsed uploads via:
1366
1367 post '/some/route' => sub {
1368 my $file = upload('file_input_foo');
1369 # file is a Dancer::Request::Upload object
1370 };
1371
1372 If you named multiple inputs of type "file" with the same name, the
1373 upload keyword will return an Array of Dancer::Request::Upload objects:
1374
1375 post '/some/route' => sub {
1376 my ($file1, $file2) = upload('files_input');
1377 # $file1 and $file2 are Dancer::Request::Upload objects
1378 };
1379
1380 You can also access the raw HashRef of parsed uploads via the current
1381 request object:
1382
1383 post '/some/route' => sub {
1384 my $all_uploads = request->uploads;
1385 # $all_uploads->{'file_input_foo'} is a Dancer::Request::Upload object
1386 # $all_uploads->{'files_input'} is an ArrayRef of Dancer::Request::Upload objects
1387 };
1388
1389 Note that you can also access the filename of the upload received via
1390 the params keyword:
1391
1392 post '/some/route' => sub {
1393 # params->{'files_input'} is the filename of the file uploaded
1394 };
1395
1396 See Dancer::Request::Upload for details about the interface provided.
1397
1398 uri_for
1399
1400 Returns a fully-qualified URI for the given path:
1401
1402 get '/' => sub {
1403 redirect uri_for('/path');
1404 # can be something like: http://localhost:3000/path
1405 };
1406
1407 Querystring parameters can be provided by passing a hashref as a second
1408 param, and URL-encoding can be disabled via a third parameter:
1409
1410 uri_for('/path', { foo => 'bar' }, 1);
1411 # would return e.g. http://localhost:3000/path?foo=bar
1412
1413 captures
1414
1415 Returns a reference to a copy of %+, if there are named captures in the
1416 route Regexp.
1417
1418 Named captures are a feature of Perl 5.10, and are not supported in
1419 earlier versions:
1420
1421 get qr{
1422 / (?<object> user | ticket | comment )
1423 / (?<action> delete | find )
1424 / (?<id> \d+ )
1425 /?$
1426 }x
1427 , sub {
1428 my $value_for = captures;
1429 "i don't want to $$value_for{action} the $$value_for{object} $$value_for{id} !"
1430 };
1431
1432 var
1433
1434 Provides an accessor for variables shared between filters and route
1435 handlers. Given a key/value pair, it sets a variable:
1436
1437 hook before sub {
1438 var foo => 42;
1439 };
1440
1441 Later, route handlers and other filters will be able to read that
1442 variable:
1443
1444 get '/path' => sub {
1445 my $foo = var 'foo';
1446 ...
1447 };
1448
1449 vars
1450
1451 Returns the HashRef of all shared variables set during the filter/route
1452 chain with the var keyword:
1453
1454 get '/path' => sub {
1455 if (vars->{foo} eq 42) {
1456 ...
1457 }
1458 };
1459
1460 warning
1461
1462 Logs a warning message through the current logger engine:
1463
1464 warning "This is a warning";
1465
1466 See Dancer::Logger for details on how to configure where log messages
1467 go.
1468
1469AUTHOR
1470
1471 This module has been written by Alexis Sukrieh <sukria@cpan.org> and
1472 others, see the AUTHORS file that comes with this distribution for
1473 details.
1474
1475SOURCE CODE
1476
1477 The source code for this module is hosted on GitHub
1478 https://github.com/PerlDancer/Dancer. Feel free to fork the repository
1479 and submit pull requests! (See Dancer::Development for details on how
1480 to contribute).
1481
1482 Also, why not watch the repo
1483 <https://github.com/PerlDancer/Dancer/toggle_watch> to keep up to date
1484 with the latest upcoming changes?
1485
1486GETTING HELP / CONTRIBUTING
1487
1488 The Dancer development team can be found on #dancer on irc.perl.org:
1489 irc://irc.perl.org/dancer
1490
1491 If you don't have an IRC client installed/configured, there is a simple
1492 web chat client at http://www.perldancer.org/irc for you.
1493
1494 There is also a Dancer users mailing list available. Subscribe at:
1495
1496 http://lists.preshweb.co.uk/mailman/listinfo/dancer-users
1497
1498 If you'd like to contribute to the Dancer project, please see
1499 http://www.perldancer.org/contribute for all the ways you can help!
1500
1501DEPENDENCIES
1502
1503 The following modules are mandatory (Dancer cannot run without them):
1504
1505 HTTP::Server::Simple::PSGI
1506
1507 HTTP::Tiny
1508
1509 MIME::Types
1510
1511 URI
1512
1513 The following modules are optional:
1514
1515 JSON : needed to use JSON serializer
1516
1517 Plack : in order to use PSGI
1518
1519 Template : in order to use TT for rendering views
1520
1521 XML::Simple and XML:SAX or XML:Parser for XML serialization
1522
1523 YAML : needed for configuration file support
1524
1525SEE ALSO
1526
1527 Main Dancer web site: http://perldancer.org/.
1528
1529 The concept behind this module comes from the Sinatra ruby project, see
1530 http://www.sinatrarb.com/ for details.
1531
1532AUTHOR
1533
1534 Dancer Core Developers
1535
1536COPYRIGHT AND LICENSE
1537
1538 This software is copyright (c) 2010 by Alexis Sukrieh.
1539
1540 This is free software; you can redistribute it and/or modify it under
1541 the same terms as the Perl 5 programming language system itself.
1542
1543