1Dancer(3)             User Contributed Perl Documentation            Dancer(3)
2
3
4

NAME

6       Dancer - lightweight yet powerful web application framework
7

VERSION

9       version 1.3400
10

SYNOPSIS

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

DESCRIPTION

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

MORE DOCUMENTATION

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

EXPORTS

63       By default, "use Dancer" exports all the functions below plus sets up
64       your app.  You can control the exporting through the normal Exporter
65       mechanism.  For example:
66
67           # Just export the route controllers
68           use Dancer qw(get post put patch del);
69
70           # Export everything but pass to avoid clashing with Test::More
71           use Test::More;
72           use Dancer qw(!pass);
73
74       Please note that the utf8 and strict pragmas are exported by this
75       module.
76
77       By default, the warnings pragma will also be exported, meaning your
78       app/script will be running under "use warnings".  If you do not want
79       this, set the global_warnings setting to a false value.
80
81       There are also some special tags to control exports and behaviour.
82
83   :moose
84       This will export everything except functions which clash with Moose.
85       Currently these are "after" and "before".
86
87   :syntax
88       This tells Dancer to just export symbols and not set up your app.  This
89       is most useful for writing Dancer code outside of your main route
90       handler.
91
92   :tests
93       This will export everything except functions which clash with commonly
94       used testing modules. Currently these are "pass".
95
96       It can be combined with other export pragmas. For example, while
97       testing...
98
99           use Test::More;
100           use Dancer qw(:syntax :tests);
101
102           # Test::Most also exports "set" and "any"
103           use Test::Most;
104           use Dancer qw(:syntax :tests !set !any);
105
106           # Alternatively, if you want to use Dancer's set and any...
107           use Test::Most qw(!set !any);
108           use Dancer qw(:syntax :tests);
109
110   :script
111       This will export all the keywords, load the configuration, and will not
112       try to parse command-line arguments via Dancer::GetOpt.
113
114       This is useful when you want to use your Dancer application from a
115       script.
116
117           use MyApp;
118           use Dancer ':script';
119           MyApp::schema('DBSchema')->deploy();
120
121       Note that using ":script"  will disable command-line parsing for all
122       subsequent invocations of "use Dancer" (such that you don't have to use
123       ":script" for each and every module to make sure the command-line
124       arguments don't get stolen by Dancer).
125
126   !keyword
127       If you want to simply prevent Dancer from exporting specific keywords
128       (perhaps you plan to implement them yourself in a different way, or you
129       don't plan to use them and they clash with another module you're
130       loading), you can simply exclude them:
131
132           use Dancer qw(!session);
133
134       The above would import all keywords as normal, with the exception of
135       "session".
136

FUNCTIONS

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

AUTHOR

1360       This module has been written by Alexis Sukrieh <sukria@cpan.org> and
1361       others, see the AUTHORS file that comes with this distribution for
1362       details.
1363

SOURCE CODE

1365       The source code for this module is hosted on GitHub
1366       <https://github.com/PerlDancer/Dancer>.  Feel free to fork the
1367       repository and submit pull requests!  (See Dancer::Development for
1368       details on how to contribute).
1369
1370       Also, why not watch the repo
1371       <https://github.com/PerlDancer/Dancer/toggle_watch> to keep up to date
1372       with the latest upcoming changes?
1373

GETTING HELP / CONTRIBUTING

1375       The Dancer development team can be found on #dancer on irc.perl.org:
1376       <irc://irc.perl.org/dancer>
1377
1378       If you don't have an IRC client installed/configured, there is a simple
1379       web chat client at <http://www.perldancer.org/irc> for you.
1380
1381       There is also a Dancer users mailing list available. Subscribe at:
1382
1383       <http://lists.preshweb.co.uk/mailman/listinfo/dancer-users>
1384
1385       If you'd like to contribute to the Dancer project, please see
1386       <http://www.perldancer.org/contribute> for all the ways you can help!
1387

DEPENDENCIES

1389       The following modules are mandatory (Dancer cannot run without them):
1390
1391       HTTP::Server::Simple::PSGI
1392       HTTP::Tiny
1393       MIME::Types
1394       URI
1395
1396       The following modules are optional:
1397
1398       JSON : needed to use JSON serializer
1399       Plack : in order to use PSGI
1400       Template : in order to use TT for rendering views
1401       XML::Simple and <XML:SAX> or <XML:Parser> for XML serialization
1402       YAML : needed for configuration file support
1403

SEE ALSO

1405       Main Dancer web site: <http://perldancer.org/>.
1406
1407       The concept behind this module comes from the Sinatra ruby project, see
1408       <http://www.sinatrarb.com/> for details.
1409

AUTHOR

1411       Dancer Core Developers
1412
1414       This software is copyright (c) 2010 by Alexis Sukrieh.
1415
1416       This is free software; you can redistribute it and/or modify it under
1417       the same terms as the Perl 5 programming language system itself.
1418
1419
1420
1421perl v5.28.0                      2018-06-15                         Dancer(3)
Impressum