/
README
1375 lines (1008 loc) · 41.6 KB
/
README
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
NAME
Dancer - lightweight yet powerful web application framework
VERSION
version 1.3131
SYNOPSIS
#!/usr/bin/perl
use Dancer;
get '/hello/:name' => sub {
return "Why, hello there " . param('name');
};
dance;
The above is a basic but functional web app created with Dancer. If you
want to see more examples and get up and running quickly, check out the
Dancer::Introduction and the Dancer::Cookbook. For examples on deploying
your Dancer applications, see Dancer::Deployment.
DESCRIPTION
Dancer is a web application framework designed to be as effortless as
possible for the developer, taking care of the boring bits as easily as
possible, yet staying out of your way and letting you get on with
writing your code.
Dancer aims to provide the simplest way for writing web applications,
and offers the flexibility to scale between a very simple lightweight
web service consisting of a few lines of code in a single file, all the
way up to a more complex fully-fledged web application with session
support, templates for views and layouts, etc.
If you don't want to write CGI scripts by hand, and find Catalyst too
big or cumbersome for your project, Dancer is what you need.
Dancer has few pre-requisites, so your Dancer webapps will be easy to
deploy.
Dancer apps can be used with a an embedded web server (great for easy
testing), and can run under PSGI/Plack for easy deployment in a variety
of webserver environments.
MORE DOCUMENTATION
This documentation describes all the exported symbols of Dancer. If you
want a quick start guide to discover the framework, you should look at
Dancer::Introduction, or Dancer::Tutorial to learn by example.
If you want to have specific examples of code for real-life problems,
see the Dancer::Cookbook.
If you want to see configuration examples of different deployment
solutions involving Dancer and Plack, see Dancer::Deployment.
You can find out more about the many useful plugins available for Dancer
in Dancer::Plugins.
EXPORTS
By default, "use Dancer" exports all the functions below plus sets up
your app. You can control the exporting through the normal Exporter
mechanism. For example:
# Just export the route controllers
use Dancer qw(get post put patch del);
# Export everything but pass to avoid clashing with Test::More
use Test::More;
use Dancer qw(!pass);
There are also some special tags to control exports and behaviour.
:moose
This will export everything except functions which clash with Moose.
Currently these are "after" and "before".
:syntax
This tells Dancer to just export symbols and not set up your app. This
is most useful for writing Dancer code outside of your main route
handler.
:tests
This will export everything except functions which clash with commonly
used testing modules. Currently these are "pass".
It can be combined with other export pragmas. For example, while
testing...
use Test::More;
use Dancer qw(:syntax :tests);
# Test::Most also exports "set" and "any"
use Test::Most;
use Dancer qw(:syntax :tests !set !any);
# Alternatively, if you want to use Dancer's set and any...
use Test::Most qw(!set !any);
use Dancer qw(:syntax :tests);
:script
This will export all the keywords, and will also load the configuration.
This is useful when you want to use your Dancer application from a
script.
use MyApp;
use Dancer ':script';
MyApp::schema('DBSchema')->deploy();
By default, the warnings pragma will also be exported, meaning your
app/script will be running under "use warnings". If you do not want
this, set the import_warnings setting to a false value.
!keyword
If you want to simply prevent Dancer from exporting specific keywords
(perhaps you plan to implement them yourself in a different way, or you
don't plan to use them and they clash with another module you're
loading), you can simply exclude them:
use Dancer qw(!session);
The above would import all keywords as normal, with the exception of
"session".
FUNCTIONS
after
Deprecated - see the "after" hook.
any
Defines a route for multiple HTTP methods at once:
any ['get', 'post'] => '/myaction' => sub {
# code
};
Or even, a route handler that would match any HTTP methods:
any '/myaction' => sub {
# code
};
before
Deprecated - see the "before" hook.
before_template
Deprecated - see the "before_template" hook.
cookies
Accesses cookies values, it returns a HashRef of Dancer::Cookie objects:
get '/some_action' => sub {
my $cookie = cookies->{name};
return $cookie->value;
};
In the case you have stored something else than a Scalar in your cookie:
get '/some_action' => sub {
my $cookie = cookies->{oauth};
my %values = $cookie->value;
return ($values{token}, $values{token_secret});
};
cookie
Accesses a cookie value (or sets it). Note that this method will
eventually be preferred over "set_cookie".
cookie lang => "fr-FR"; # set a cookie and return its value
cookie lang => "fr-FR", expires => "2 hours"; # extra cookie info
cookie "lang" # return a cookie value
If your cookie value is a key/value URI string, like
token=ABC&user=foo
"cookie" will only return the first part ("token=ABC") if called in
scalar context. Use list context to fetch them all:
my @values = cookie "name";
config
Accesses the configuration of the application:
get '/appname' => sub {
return "This is " . config->{appname};
};
content_type
Sets the content-type rendered, for the current route handler:
get '/cat/:txtfile' => sub {
content_type 'text/plain';
# here we can dump the contents of param('txtfile')
};
You can use abbreviations for content types. For instance:
get '/svg/:id' => sub {
content_type 'svg';
# here we can dump the image with id param('id')
};
Note that if you want to change the default content-type for every
route, you have to change the "content_type" setting instead.
dance
Alias for the "start" keyword.
dancer_version
Returns the version of Dancer. If you need the major version, do
something like:
int(dancer_version);
debug
Logs a message of debug level:
debug "This is a debug message";
See Dancer::Logger for details on how to configure where log messages
go.
dirname
Returns the dirname of the path given:
my $dir = dirname($some_path);
engine
Given a namespace, returns the current engine object
my $template_engine = engine 'template';
my $html = $template_engine->apply_renderer(...);
$template_engine->apply_layout($html);
error
Logs a message of error level:
error "This is an error message";
See Dancer::Logger for details on how to configure where log messages
go.
false
Constant that returns a false value (0).
forward
Runs an internal redirect of the current request to another request.
This helps you avoid having to redirect the user using HTTP and set
another request to your application.
It effectively lets you chain routes together in a clean manner.
get '/demo/articles/:article_id' => sub {
# you'll have to implement this next sub yourself :)
change_the_main_database_to_demo();
forward "/articles/" . params->{article_id};
};
In the above example, the users that reach */demo/articles/30* will
actually reach */articles/30* but we've changed the database to demo
before.
This is pretty cool because it lets us retain our paths and offer a demo
database by merely going to */demo/...*.
You'll notice that in the example we didn't indicate whether it was GET
or POST. That is because "forward" chains the same type of route the
user reached. If it was a GET, it will remain a GET (but if you do need
to change the method, you can do so; read on below for details.)
WARNING : using forward will not preserve session data set on the
forwarding rule.
WARNING : Issuing a forward immediately exits the current route, and
perform the forward. Thus, any code after a forward is ignored, until
the end of the route. e.g.
get '/foo/:article_id' => sub {
if ($condition) {
forward "/articles/" . params->{article_id};
# The following code is never executed
do_stuff();
}
more_stuff();
};
So it's not necessary anymore to use "return" with forward.
Note that forward doesn't parse GET arguments. So, you can't use
something like:
return forward '/home?authorized=1';
But "forward" supports an optional HashRef with parameters to be added
to the actual parameters:
return forward '/home', { authorized => 1 };
Finally, you can add some more options to the forward method, in a third
argument, also as a HashRef. That option is currently only used to
change the method of your request. Use with caution.
return forward '/home', { auth => 1 }, { method => 'POST' };
from_dumper ($structure)
Deserializes a Data::Dumper structure.
from_json ($structure, %options)
Deserializes a JSON structure. Can receive optional arguments. Those
arguments are valid JSON arguments to change the behaviour of the
default "JSON::from_json" function.
from_yaml ($structure)
Deserializes a YAML structure.
from_xml ($structure, %options)
Deserializes a XML structure. Can receive optional arguments. These
arguments are valid XML::Simple arguments to change the behaviour of the
default "XML::Simple::XMLin" function.
get
Defines a route for HTTP GET requests to the given path:
get '/' => sub {
return "Hello world";
}
Note that a route to match HEAD requests is automatically created as
well.
halt
Sets a response object with the content given.
When used as a return value from a filter, this breaks the execution
flow and renders the response immediately:
hook before sub {
if ($some_condition) {
halt("Unauthorized");
# This code is not executed :
do_stuff();
}
};
get '/' => sub {
"hello there";
};
WARNING : Issuing a halt immediately exits the current route, and
perform the halt. Thus, any code after a halt is ignored, until the end
of the route. So it's not necessary anymore to use "return" with halt.
headers
Adds custom headers to responses:
get '/send/headers', sub {
headers 'X-Foo' => 'bar', X-Bar => 'foo';
}
header
adds a custom header to response:
get '/send/header', sub {
header 'x-my-header' => 'shazam!';
}
Note that it will overwrite the old value of the header, if any. To
avoid that, see "push_header".
push_header
Do the same as "header", but allow for multiple headers with the same
name.
get '/send/header', sub {
push_header 'x-my-header' => '1';
push_header 'x-my-header' => '2';
will result in two headers "x-my-header" in the response
}
hook
Adds a hook at some position. For example :
hook before_serializer => sub {
my $response = shift;
$response->content->{generated_at} = localtime();
};
There can be multiple hooks assigned to a given position, and each will
be executed in order. Note that all hooks are always called, even if
they are defined in a different package loaded via "load_app".
(For details on how to register new hooks from within plugins, see
Dancer::Hook.) Supported before hooks (in order of execution):
before_deserializer
This hook receives no arguments.
hook before_deserializer => sub {
...
};
before_file_render
This hook receives as argument the path of the file to render.
hook before_file_render => sub {
my $path = shift;
...
};
before_error_init
This hook receives as argument a Dancer::Error object.
hook before_error_init => sub {
my $error = shift;
...
};
before_error_render
This hook receives as argument a Dancer::Error object.
hook before_error_render => sub {
my $error = shift;
};
before
This hook receives one argument, the route being executed (a
Dancer::Route object).
hook before => sub {
my $route_handler = shift;
...
};
it is equivalent to the deprecated
before sub {
...
};
before_template_render
This is an alias to 'before_template'.
This hook receives as argument a HashRef, containing the tokens that
will be passed to the template. You can use it to add more tokens,
or delete some specific token.
hook before_template_render => sub {
my $tokens = shift;
delete $tokens->{user};
$tokens->{time} = localtime;
};
is equivalent to
hook before_template => sub {
my $tokens = shift;
delete $tokens->{user};
$tokens->{time} = localtime;
};
before_layout_render
This hook receives two arguments. The first one is a HashRef
containing the tokens. The second is a ScalarRef representing the
content of the template.
hook before_layout_render => sub {
my ($tokens, $html_ref) = @_;
...
};
before_serializer
This hook receives as argument a Dancer::Response object.
hook before_serializer => sub {
my $response = shift;
$response->content->{start_time} = time();
};
Supported after hooks (in order of execution):
after_deserializer
This hook receives no arguments.
hook after_deserializer => sub {
...
};
after_file_render
This hook receives as argument a Dancer::Response object.
hook after_file_render => sub {
my $response = shift;
};
after_template_render
This hook receives as argument a ScalarRef representing the content
generated by the template.
hook after_template_render => sub {
my $html_ref = shift;
};
after_layout_render
This hook receives as argument a ScalarRef representing the content
generated by the layout
hook after_layout_render => sub {
my $html_ref = shift;
};
after
This is an alias for "after".
This hook runs after a request has been processed, but before the
response is sent.
It receives a Dancer::Response object, which it can modify if it
needs to make changes to the response which is about to be sent.
hook after => sub {
my $response = shift;
};
This is equivalent to the deprecated
after sub {
my $response = shift;
};
after_error_render
This hook receives as argument a Dancer::Response object.
hook after_error_render => sub {
my $response = shift;
};
on_handler_exception
This hook is called when an exception has been caught, at the
handler level, just before creating and rendering Dancer::Error.
This hook receives as argument a Dancer::Exception object.
hook on_handler_exception => sub {
my $exception = shift;
};
on_reset_state
This hook is called when global state is reset to process a new
request. It receives a boolean value that indicates whether the
reset was called as part of a forwarded request.
hook on_reset_state => sub {
my $is_forward = shift;
};
on_route_exception
This hook is called when an exception has been caught, at the route
level, just before rethrowing it higher. This hook receives the
exception as argument. It can be a Dancer::Exception, or a string,
or whatever was used to "die".
hook on_route_exception => sub {
my $exception = shift;
};
info
Logs a message of info level:
info "This is a info message";
See Dancer::Logger for details on how to configure where log messages
go.
layout
This method is deprecated. Use "set":
set layout => 'user';
logger
Deprecated. Use "<set logger => 'console'"> to change current logger
engine.
load
Loads one or more perl scripts in the current application's namespace.
Syntactic sugar around Perl's "require":
load 'UserActions.pl', 'AdminActions.pl';
load_app
Loads a Dancer package. This method sets the libdir to the current
"./lib" directory:
# if we have lib/Webapp.pm, we can load it like:
load_app 'Webapp';
# or with options
load_app 'Forum', prefix => '/forum', settings => {foo => 'bar'};
Note that the package loaded using load_app must import Dancer with the
":syntax" option.
To load multiple apps repeat load_app:
load_app 'one';
load_app 'two';
The old way of loading multiple apps in one go (load_app 'one', 'two';)
is deprecated.
mime
Shortcut to access the instance object of Dancer::MIME. You should read
the Dancer::MIME documentation for full details, but the most
commonly-used methods are summarized below:
# set a new mime type
mime->add_type( foo => 'text/foo' );
# set a mime type alias
mime->add_alias( f => 'foo' );
# get mime type for an alias
my $m = mime->for_name( 'f' );
# get mime type for a file (based on extension)
my $m = mime->for_file( "foo.bar" );
# get current defined default mime type
my $d = mime->default;
# set the default mime type using config.yml
# or using the set keyword
set default_mime_type => 'text/plain';
params
*This method should be called from a route handler*. It's an alias for
the Dancer::Request params accessor. In list context it returns a list
of key/value pair of all defined parameters. In scalar context, it
returns a hash reference instead. Check "param" below to access quickly
to a single parameter value.
param
*This method should be called from a route handler*. This method is an
accessor to the parameters hash table.
post '/login' => sub {
my $username = param "user";
my $password = param "pass";
# ...
}
pass
*This method should be called from a route handler*. Tells Dancer to
pass the processing of the request to the next matching route.
WARNING : Issuing a pass immediately exits the current route, and
perform the pass. Thus, any code after a pass is ignored, until the end
of the route. So it's not necessary anymore to use "return" with pass.
get '/some/route' => sub {
if (...) {
# we want to let the next matching route handler process this one
pass(...);
# This code will be ignored
do_stuff();
}
};
patch
Defines a route for HTTP PATCH requests to the given URL:
patch '/resource' => sub { ... };
("PATCH" is a relatively new and not-yet-common HTTP verb, which is
intended to work as a "partial-PUT", transferring just the changes;
please see <http://tools.ietf.org/html/rfc5789|RFC5789> for further
details.)
Please be aware that, if you run your app in standalone mode, "PATCH"
requests will not reach your app unless you have a new version of
HTTP::Server::Simple which accepts "PATCH" as a valid verb. The current
version at time of writing, 0.44, does not. A pull request has been
submitted to add this support, which you can find at:
<https://github.com/bestpractical/http-server-simple/pull/1>
path
Concatenates multiple paths together, without worrying about the
underlying operating system:
my $path = path(dirname($0), 'lib', 'File.pm');
It also normalizes (cleans) the path aesthetically. It does not verify
the path exists.
post
Defines a route for HTTP POST requests to the given URL:
post '/' => sub {
return "Hello world";
}
prefix
Defines a prefix for each route handler, like this:
prefix '/home';
From here, any route handler is defined to /home/*:
get '/page1' => sub {}; # will match '/home/page1'
You can unset the prefix value:
prefix undef;
get '/page1' => sub {}; will match /page1
For a safer alternative you can use lexical prefix like this:
prefix '/home' => sub {
## Prefix is set to '/home' here
get ...;
get ...;
};
## prefix reset to the previous version here
This makes it possible to nest prefixes:
prefix '/home' => sub {
## some routes
prefix '/private' => sub {
## here we are under /home/private...
## some more routes
};
## back to /home
};
## back to the root
Notice: once you have a prefix set, do not add a caret to the regex:
prefix '/foo';
get qr{^/bar} => sub { ... } # BAD BAD BAD
get qr{/bar} => sub { ... } # Good!
del
Defines a route for HTTP DELETE requests to the given URL:
del '/resource' => sub { ... };
options
Defines a route for HTTP OPTIONS requests to the given URL:
options '/resource' => sub { ... };
put
Defines a route for HTTP PUT requests to the given URL:
put '/resource' => sub { ... };
redirect
Generates a HTTP redirect (302). You can either redirect to a complete
different site or within the application:
get '/twitter', sub {
redirect 'http://twitter.com/me';
};
You can also force Dancer to return a specific 300-ish HTTP response
code:
get '/old/:resource', sub {
redirect '/new/'.params->{resource}, 301;
};
It is important to note that issuing a redirect by itself does not exit
and redirect immediately, redirection is deferred until after the
current route or filter has been processed. To exit and redirect
immediately, use the return function, e.g.
get '/restricted', sub {
return redirect '/login' if accessDenied();
return 'Welcome to the restricted section';
};
render_with_layout
Allows a handler to provide plain HTML (or other content), but have it
rendered within the layout still.
This method is DEPRECATED, and will be removed soon. Instead, you should
be using the "engine" keyword:
get '/foo' => sub {
# Do something which generates HTML directly (maybe using
# HTML::Table::FromDatabase or something)
my $content = ...;
# get the template engine
my $template_engine = engine 'template';
# apply the layout (not the renderer), and return the result
$template_engine->apply_layout($content)
};
It works very similarly to "template" in that you can pass tokens to be
used in the layout, and/or options to control the way the layout is
rendered. For instance, to use a custom layout:
render_with_layout $content, {}, { layout => 'layoutname' };
request
Returns a Dancer::Request object representing the current request.
See the Dancer::Request documentation for the methods you can call, for
example:
request->referer; # value of the HTTP referer header
request->remote_address; # user's IP address
request->user_agent; # User-Agent header value
send_error
Returns a HTTP error. By default the HTTP code returned is 500:
get '/photo/:id' => sub {
if (...) {
send_error("Not allowed", 403);
} else {
# return content
}
}
WARNING : Issuing a send_error immediately exits the current route, and
perform the send_error. Thus, any code after a send_error is ignored,
until the end of the route. So it's not necessary anymore to use
"return" with send_error.
get '/some/route' => sub {
if (...) {
# we want to let the next matching route handler process this one
send_error(..);
# This code will be ignored
do_stuff();
}
};
send_file
Lets the current route handler send a file to the client. Note that the
path of the file must be relative to the public directory unless you use
the "system_path" option (see below).
get '/download/:file' => sub {
return send_file(params->{file});
}
WARNING : Issuing a send_file immediately exits the current route, and
perform the send_file. Thus, any code after a send_file is ignored,
until the end of the route. So it's not necessary anymore to use
"return" with send_file.
get '/some/route' => sub {
if (...) {
# we want to let the next matching route handler process this one
send_file(...);
# This code will be ignored
do_stuff();
}
};
Send file supports streaming possibility using PSGI streaming. The
server should support it but normal streaming is supported on most, if
not all.
get '/download/:file' => sub {
return send_file( params->{file}, streaming => 1 );
}
You can control what happens using callbacks.
First, "around_content" allows you to get the writer object and the
chunk of content read, and then decide what to do with each chunk:
get '/download/:file' => sub {
return send_file(
params->{file},
streaming => 1,
callbacks => {
around_content => sub {
my ( $writer, $chunk ) = @_;
$writer->write("* $chunk");
},
},
);
}
You can use "around" to all get all the content (whether a filehandle if
it's a regular file or a full string if it's a scalar ref) and decide
what to do with it:
get '/download/:file' => sub {
return send_file(
params->{file},
streaming => 1,
callbacks => {
around => sub {
my ( $writer, $content ) = @_;
# we know it's a text file, so we'll just stream
# line by line
while ( my $line = <$content> ) {
$writer->write($line);
}
},
},
);
}
Or you could use "override" to control the entire streaming callback
request:
get '/download/:file' => sub {
return send_file(
params->{file},
streaming => 1,
callbacks => {
override => sub {
my ( $respond, $response ) = @_;
my $writer = $respond->( [ $newstatus, $newheaders ] );
$writer->write("some line");
},
},
);
}
You can also set the number of bytes that will be read at a time
(default being 42K bytes) using "bytes":
get '/download/:file' => sub {
return send_file(
params->{file},
streaming => 1,
bytes => 524288, # 512K
);
};
The content-type will be set depending on the current MIME types
definition (see "mime" if you want to define your own).
If your filename does not have an extension, or you need to force a
specific mime type, you can pass it to "send_file" as follows:
return send_file(params->{file}, content_type => 'image/png');
Also, you can use your aliases or file extension names on
"content_type", like this:
return send_file(params->{file}, content_type => 'png');
For files outside your public folder, you can use the "system_path"
switch. Just bear in mind that its use needs caution as it can be
dangerous.
return send_file('/etc/passwd', system_path => 1);
If you have your data in a scalar variable, "send_file" can be useful as
well. Pass a reference to that scalar, and "send_file" will behave as if
there was a file with that contents:
return send_file( \$data, content_type => 'image/png' );
Note that Dancer is unable to guess the content type from the data
contents. Therefore you might need to set the "content_type" properly.
For this kind of usage an attribute named "filename" can be useful. It
is used as the Content-Disposition header, to hint the browser about the
filename it should use.
return send_file( \$data, content_type => 'image/png'
filename => 'onion.png' );
Note that you should always use "return send_file ..." to stop execution
of your route handler at that point.
set
Defines a setting:
set something => 'value';
You can set more than one value at once:
set something => 'value', otherthing => 'othervalue';
setting
Returns the value of a given setting:
setting('something'); # 'value'
set_cookie
Creates or updates cookie values: