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