summaryrefslogtreecommitdiff
path: root/lib/Dancer2/Manual/Keywords.pod
blob: a37d2e6e20b976ae670cd5081a87d6a3b9d39ca7 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
# ABSTRACT: Dancer2 DSL Keywords
package Dancer2::Manual::Keywords;

__END__

=pod

=encoding UTF-8

=head1 NAME

Dancer2::Manual::Keywords - Dancer2 DSL Keywords

=head1 VERSION

version 1.1.0

=head1 DSL KEYWORDS

Dancer2 provides you with a DSL (Domain-Specific Language) which makes
implementing your web application trivial.

For example, take the following example:

    use Dancer2;

    get '/hello/:name' => sub {
        my $name = route_parameters->get('name');
    };
    true;

C<get> and C<route_parameters> are keywords provided by Dancer2.

This document lists all keywords provided by Dancer2. It does not cover
additional keywords which may be provided by loaded plugins; see the
documentation for plugins you use to see which additional keywords they make
available to you.

=head2 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
    };

=head2 app

Returns an instance of the app. App is a L<Dancer2::Core::App>.

=head2 body_parameters

Returns a L<Hash::MultiValue> object from the body parameters.

    post '/' => sub {
        my $last_name = body_parameters->get('name');
        my @all_names = body_parameters->get_all('name');
    };

=head2 captures

Returns a reference to a copy of C<%+>, if there are named captures in the
route's regular expression.

    get qr{
        / (?<object> user   | ticket | comment )
        / (?<action> delete | find )
        / (?<id> \d+ )
        /?$
    }x
    , sub {
        my $value_for = captures;
        "i don't want to $value_for->{action} " . 
            "the $value_for->{object} $value_for->{id} !"
    };

=head2 cookie

Accesses a cookie value (or sets it). Note that this method will eventually
be preferred over C<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

C<cookie> will only return the first part (C<token=ABC>) if called in scalar
context. Use list context to fetch them all:

    my @values = cookie "name";

=head2 cookies

Accesses cookies values, it returns a hashref of L<Dancer2::Core::Cookie>
objects:

    get '/some_action' => sub {
        my $cookie = cookies->{name};
        return $cookie->value;
    };

In case you have stored something other than a scalar in your cookie:

    get '/some_action' => sub {
        my $cookie = cookies->{oauth};
        my %values = $cookie->value;
        return ($values{token}, $values{token_secret});
    };

=head2 config

Accesses the configuration of the application:

    get '/appname' => sub {
        return "This is " . config->{appname};
    };

=head2 content

Sets the content for the response. This B<only> works within a delayed
response.

This will crash:

    get '/' => sub {
        # THIS WILL CRASH
        content 'Hello, world!';
    };

But this will work just fine:

    get '/' => sub {
        delayed {
            content 'Hello, world!';
            ...
        };
    };

=head2 content_type

Sets the B<content-type> rendered, for the current route handler:

    get '/cat/:txtfile' => sub {
        content_type 'text/plain';

        # here we can dump the contents of route_parameters->get('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 route_parameters->get('id')
    };

Note that if you want to change the default content-type for every route,
it is easier to change the C<content_type> setting instead.

=head2 context

Deprecated. Use L</app> instead.

=head2 dance

Alias for the C<start> keyword. L</to_app> is preferable.

=head2 dancer_app

Returns the app object. See L</app>.

=head2 dancer_version

Returns the version of Dancer. If you need the major version, do something
like:

    int(dancer_version);

or (better), call C<dancer_major_version>.

=head2 dancer_major_version

Returns the major version of Dancer.

=head2 debug

Logs a message of debug level:

    debug "This is a debug message";

See L<Dancer2::Core::Role::Logger> for details on how to configure where log
messages go.

=head2 decode_json ($string)

Deserializes a JSON structure from an UTF-8 binary string.

=head2 del

Defines a route for HTTP B<DELETE> requests to the given URL:

    del '/resource' => sub { ... };

You can also provide the route with a name:

    del 'rec' => '/resource' => sub { ... };

See C<uri_for_route> on how this can be used.

=head2 delayed

Stream a response asynchronously. For more information, please see 
L<Dancer2::Manual/Delayed responses (Async/Streaming)>, or 
L<this article|https://advent.perldancer.org/2020/22> in the 2020 Dancer 
Advent Calendar.

=head2 dirname

Returns the dirname of the path given:

    my $dir = dirname($some_path);

=head2 done

Close the streaming connection. Can only be called within a streaming 
response callback.

=head2 dsl

Allows access to the DSL within your plugin/application. Is an instance of
L<Dancer2::Core::DSL>.

=head2 encode_json ($structure)

Serializes a structure to a UTF-8 binary JSON string.

Calling this function will B<not> trigger the serialization's hooks.

=head2 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);

=head2 error

Logs a message of error level:

    error "This is an error message";

See L<Dancer2::Core::Role::Logger> for details on how to configure where log
messages go.

=head2 false

Constant that returns a false value (0).

=head2 flush

Flush headers when streaming a response. Necessary when L</content> is called
multiple times.

=head2 forward

Runs an "internal redirect" of the current route to another route. More
formally; when C<forward> is executed, the current dispatch of the route is
aborted, the request is modified (altering query params or request method),
and the modified request following a new route is dispatched again. Any
remaining code (route and hooks) from the current dispatch will never be run
and the modified route's dispatch will execute hooks for the new route normally.

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/" . route_parameters->get('article_id');
    };

In the above example, the users that reach I</demo/articles/30> will
actually reach I</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 I</demo/...>.

You'll notice that in the example we didn't indicate whether it was B<GET>
or B<POST>. That is because C<forward> chains the same type of route the
user reached. If it was a B<GET>, it will remain a B<GET> (but if you do
need to change the method, you can do so; read on below for details.)

Also notice that C<forward> only redirects to a new route. It does not redirect
the requests involving static files. This is because static files are handled
before L<Dancer2> tries to match the request to a route - static files take
higher precedence.

This means that you will not be able to C<forward> to a static file. If you
wish to do so, you have two options: either redirect (asking the browser to
make another request, but to a file path instead) or use C<send_file> to
provide a file.

B<WARNING:> Any code after a C<forward> is ignored, until the end of the
route. It's not necessary to use C<return> with C<forward> anymore.

    get '/foo/:article_id' => sub {
        if ($condition) {
            forward "/articles/" . route_parameters->get('article_id');
            # The following code WILL NOT BE executed
            do_stuff();
        }

        more_stuff();
    };

Note that C<forward> doesn't parse GET arguments. So, you can't use
something like:

    forward '/home?authorized=1';

But C<forward> supports an optional hashref with parameters to be added to
the actual parameters:

    forward '/home', { authorized => 1 };

Finally, you can add some more options to the C<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.

    forward '/home', { auth => 1 }, { method => 'POST' };

=head2 from_dumper ($structure)

Deserializes a Data::Dumper structure.

=head2 from_json ($string, \%options)

Deserializes a JSON structure from a string. You should probably use
C<decode_json> which expects a UTF-8 encoded binary string and
handles decoding it for you.

=head2 from_yaml ($structure)

Deserializes a YAML structure.

=head2 get

Defines a route for HTTP B<GET> requests to the given path:

    get '/' => sub {
        return "Hello world";
    }

Note that a route to match B<HEAD> requests is automatically created as well.

You can also provide the route with a name:

    get 'index' => '/' => sub {
        return "Hello world";
    }

See C<uri_for_route> on how this can be used.

=head2 halt

Sets a response object with the content given.

When used as a return value from a hook, 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";
    };

B<WARNING:> Issuing a halt immediately exits the current route, and performs
the halt. Thus, any code after a halt is ignored, until the end of the route.
Hence, it's not necessary anymore to use C<return> with halt.

=head2 header

Deprecated. Use L</response_header> instead.

=head2 headers

Deprecated. Use L</response_headers> instead.

=head2 hook

Adds a hook at some position. For example :

  hook before_serializer => sub {
    my $content = shift;
    ...
  };

There can be multiple hooks assigned to a given position, and each will be
executed in order.

See L<Dancer2::Manual/HOOKS> for a list of available hooks.

=head2 info

Logs a message of C<info> level:

    info "This is an info message";

See L<Dancer2::Core::Role::Logger> for details on how to configure where log
messages go.

=head2 log

Logs messages at the specified level. For example:

    log( debug => "This is a debug message." );

=head2 mime

Shortcut to access the instance object of L<Dancer2::Core::MIME>. You should
read the L<Dancer2::Core::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';

=head2 options

Defines a route for HTTP B<OPTIONS> requests to the given URL:

    options '/resource' => sub { ... };

=head2 param

I<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";
       # ...
   };

We now recommend using one of the specific keywords for parameters
(C<route_parameters>, C<query_parameters>, and C<body_parameters>)
instead of C<params> or C<param>.

=head2 params

I<This method should be called from a route handler>.
It's an alias for the L<Dancer2::Core::Request params
accessor|Dancer2::Core::Request/"params($source)">. It returns a hash (in
list context) or a hash reference (in scalar context) to all defined
parameters. Check C<param> below to access quickly to a single parameter
value.

    post '/login' => sub {
        # get all parameters as a single hash
        my %all_parameters = params;

        // request all parmameters from a specific source: body, query, route
        my %body_parameters  = params('body');
        my %route_parameters = params('route');
        my %query_parameters = params('query');

        # any $source that is not body, query, or route generates an exception
        params('fake_source'); // Unknown source params "fake_source"
    };

We now recommend using one of the specific keywords for parameters
(C<route_parameters>, C<query_parameters>, and C<body_parameters>)
instead of C<params> or C<param>.

=head2 pass

I<This method should be called from a route handler>.
Tells Dancer2 to pass the processing of the request to the next matching
route.

B<WARNING:> Issuing a pass immediately exits the current route, and performs
the pass. Thus, any code after a pass is ignored, until the end of the
route. Hence, it's not necessary anymore to use C<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();
        }
    };

B<WARNING:> You cannot set the content before passing and have it remain,
even if you use the C<content> keyword or set it directly in the response
object.

=head2 patch

Defines a route for HTTP B<PATCH> requests to the given URL:

    patch '/resource' => sub { ... };

(C<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 L<RFC5789|http://tools.ietf.org/html/rfc5789> for further details.)

You can also provide the route with a name:

    patch 'rec' => '/resource' => sub { ... };

See C<uri_for_route> on how this can be used.

=head2 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 whether
the path exists, though.

=head2 post

Defines a route for HTTP B<POST> requests to the given URL:

    post '/' => sub {
        return "Hello world";
    }

You can also provide the route with a name:

    post 'index' => '/' => sub {
        return "Hello world";
    }

See C<uri_for_route> on how this can be used.

=head2 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

B<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!

=head2 prepare_app

You can introduce code you want to run when your app is loaded, similar to the
C<prepare_app> in L<Plack::Middleware>.

    prepare_app {
        my $app = shift;

        ... # do your thing
    };

You should not close over the App instance, since you receive it as a first
argument. If you close over it, you B<will> have a memory leak.

    my $app = app();

    prepare_app {
        do_something_with_app($app); # MEMORY LEAK
    };

=head2 psgi_app

Provides the same functionality as L</to_app> but uses the deprecated
Dispatcher engine. You should use L</to_app> instead.

=head2 push_header

Deprecated. Use C<push_response_header> instead.

=head2 push_response_header

Do the same as C<response_header>, but allow for multiple headers with the same
name.

    get '/send/header', sub {
        push_response_header 'x-my-header' => '1';
        push_response_header 'x-my-header' => '2';
        # will result in two headers "x-my-header" in the response
    }

=head2 put

Defines a route for HTTP B<PUT> requests to the given URL:

    put '/resource' => sub { ... };

You can also provide the route with a name:

    put 'rec' => '/resource' => sub { ... };

See C<uri_for_route> on how this can be used.

=head2 query_parameters

Returns a L<Hash::MultiValue> object from the request parameters.

    /?foo=hello
    get '/' => sub {
        my $name = query_parameters->get('foo');
    };

    /?name=Alice&name=Bob
    get '/' => sub {
        my @names = query_parameters->get_all('name');
    };

=head2 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';
        # Any code after the redirect will not be executed.
    };

B<WARNING:> Issuing a C<redirect> immediately exits the current route.
Thus, any code after a C<redirect> is ignored, until the end of the route.
Hence, it's not necessary anymore to use C<return> with C<redirect>.

You can also force Dancer to return a specific 300-ish HTTP response code:

    get '/old/:resource', sub {
        redirect '/new/' . route_parameters->get('resource'), 301;
    };

=head2 request

Returns a L<Dancer2::Core::Request> object representing the current request.

See the L<Dancer2::Core::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

=head2 request_data

Returns the request's body in data form
(in case a serializer is set, it will be in deserialized).

This allows us to distinguish between C<body_parameters>, a representation
of request parameters (L<Hash::MultiValue>) and other forms of content.

=head2 request_header

Returns request header(s).

    get '/get/headers' => sub {
        my $xfoo = request_header 'X-Foo';
        ...
    };

=head2 response

Returns the current response object, which is of type 
L<Dancer2::Core::Route::REQUEST>.

=head2 response_header

Adds a custom header to response:

    get '/send/header', sub {
        response_header 'x-my-header' => 'shazam!';
    }

Note that it will overwrite the old value of the header, if any. To avoid
that, see L</push_response_header>.

=head2 response_headers

Adds custom headers to response:

    get '/send/headers', sub {
        response_headers 'X-Foo' => 'bar', 'X-Bar' => 'foo';
    }

=head2 route_parameters

Returns a L<Hash::MultiValue> object from the route parameters.

    # /hello
    get '/:foo' => sub {
        my $foo = route_parameters->get('foo');
    };

=head2 runner

Returns the runner singleton. Type is L<Dancer2::Core::Runner>.

=head2 send_as

Allows the current route handler to return specific content types to the
client using either a specified serializer or as html.

Any Dancer2 serializer may be used. The specified serializer class will
be loaded if required, or an error generated if the class can not be found.
Serializer configuration may be added to your apps C<engines> configuration.

If C<html> is specified, the content will be returned assuming it is HTML with
appropriate C<Content-Type> headers and encoded using the apps configured
C<charset> (or UTF-8).

    set serializer => 'YAML';
    set template   => 'TemplateToolkit';

    # returns html (not YAML)
    get '/' => sub { send_as html => template 'welcome.tt' };

    # return json (not YAML)
    get '/json' => sub {
        send_as JSON => [ some => { data => 'structure' } ];
    };

C<send_as> uses L</send_file> to return the content immediately. You may
pass any option C<send_file> supports as an extra option. For example:

    # return json with a custom content_type header
    get '/json' => sub {
        send_as JSON => [ some => { data => 'structure' } ],
                { content_type => 'application/json; charset=UTF-8' },
    };

B<WARNING:> Issuing a send_as immediately exits the current route, and
performs the C<send_as>. Thus, any code after a C<send_as> is ignored,
until the end of the route. Hence, it's not necessary to use C<return>
with C<send_as>.

    get '/some/route' => sub {
        if (...) {
            send_as JSON => $some_data;

            # this code will be ignored
            do_stuff();
        }
    };

=head2 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
        }
    }

B<WARNING:> Issuing a send_error immediately exits the current route, and
performs the C<send_error>. Thus, any code after a C<send_error> is ignored,
until the end of the route. Hence, it's not necessary anymore to use C<return>
with C<send_error>.

    get '/some/route' => sub {
        if (...) {
            # Something bad happened, stop immediately!
            send_error(..);

            # this code will be ignored
            do_stuff();
        }
    };

=head2 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 B<public> directory unless you use the
C<system_path> option (see below).

    get '/download/:file' => sub {
        return send_file(route_parameters->get('file'));
    }

B<WARNING:> Issuing a C<send_file> immediately exits the current route, and
performs the C<send_file>. Thus, any code after a C<send_file> is ignored,
until the end of the route. Hence, it's not necessary anymore to use C<return>
with C<send_file>.

    get '/some/route' => sub {
        if (...) {
            # OK, send her what she wants...
            send_file(...);

            # this code will be ignored
            do_stuff();
        }
    };

C<send_file> will use PSGI streaming if the server supports it (most, if
not all, do). You can explicitly disable streaming by passing
C<streaming =E<gt> 0> as an option to C<send_file>.

    get '/download/:file' => sub {
        send_file( route_parameters->get('file'), streaming => 0 );
    }

The content-type will be set depending on the current MIME types definition
(see C<mime> if you want to define your own).

If your filename does not have an extension, you are passing in a filehandle,
or you need to force a specific mime type, you can pass it to C<send_file>
as follows:

    send_file(route_parameters->get('file'), content_type => 'image/png');
    send_file($fh, content_type => 'image/png');

Also, you can use your aliases or file extension names on C<content_type>,
like this:

    send_file(route_parameters->get('file'), content_type => 'png');

The encoding of the file or filehandle may be specified by passing both
the C<content_type> and C<charset> options. For example:

    send_file($fh, content_type => 'text/csv', charset => 'utf-8' );

For files outside your B<public> folder, you can use the C<system_path>
switch. Just bear in mind that its use needs caution as it can be dangerous.

   send_file('/etc/passwd', system_path => 1);

If you have your data in a scalar variable, C<send_file> can be useful as
well. Pass a reference to that scalar, and C<send_file> will behave as if
there was a file with that contents:

   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 C<content_type> properly. For this kind
of usage an attribute named C<filename> can be useful. It is used as the
Content-Disposition header, to hint the browser about the filename it should
use.

   send_file( \$data, content_type => 'image/png'
                      filename     => 'onion.png' );

By default the Content-Disposition header uses the "attachment" type, which
triggers a "Save" dialog in some browsers. Supply a C<content_disposition>
attribute of "inline" to have the file displayed inline by the browser.

=head2 session

Provides access to all data stored in the user's session (if any).

It can also be used as a setter to store data in the session:

    # getter example
    get '/user' => sub {
        if (session('user')) {
            return "Hello, ".session('user')->name;
        }
    };

    # setter example
    post '/user/login' => sub {
        ...
        if ($logged_in) {
            session user => $user;
        }
        ...
    };

You may also need to clear a session:

    # destroy session
    get '/logout' => sub {
        ...
        app->destroy_session;
        ...
    };

If you need to fetch the session ID being used for any reason:

    my $id = session->id;

=head2 set

Defines a setting:

    set something => 'value';

You can set more than one value at once:

    set something => 'value', otherthing => 'othervalue';

=head2 setting

Returns the value of a given setting:

    setting('something'); # 'value'

=head2 splat

Returns the list of captures made from a route handler with a route pattern
which includes wildcards:

    get '/file/*.*' => sub {
        my ($file, $extension) = splat;
        ...
    };

There is also the extensive splat (A.K.A. "megasplat"), which allows
extensive greedier matching, available using two asterisks. The additional
path is broken down and returned as an arrayref:

    get '/entry/*/tags/**' => sub {
        my ( $entry_id, $tags ) = splat;
        my @tags = @{$tags};
    };

The C<splat> keyword in the above example for the route F</entry/1/tags/one/two>
would set C<$entry_id> to C<1> and C<$tags> to C<['one', 'two']>.

=head2 start

Starts the application or the standalone server (depending on the deployment
choices).

This keyword should be called at the very end of the script, once all routes
are defined. At this point, Dancer2 takes over.

Prefer L</to_app> instead of C<start>.

=head2 status

Changes the status code provided by an action. By default, an action will
produce an C<HTTP 200 OK> status code, meaning everything is OK:

    get '/download/:file' => {
        if (! -f route_parameters->get('file')) {
            status 'not_found';
            return "File does not exist, unable to download";
        }
        # serving the file...
    };

In that example, Dancer will notice that the status has changed, and will
render the response accordingly.

The C<status> keyword receives either a numeric status code or its name in
lower case, with underscores as a separator for blanks - see the list in
L<Dancer2::Core::HTTP/"HTTP CODES">. As an example, The above call translates
to setting the code to C<404>.

=head2 template

Returns the response of processing the given template with the given
parameters (and optional settings), wrapping it in the default or specified
layout too, if layouts are in use.

An example of a  route handler which returns the result of using template to
build a response with the current template engine:

    get '/' => sub {
        ...
        return template 'some_view', { token => 'value'};
    };

Note that C<template> simply returns the content, so when you use it in a
route handler, if execution of the route handler should stop at that point,
make sure you use C<return> to ensure your route handler returns the content.

Since C<template> just returns the result of rendering the template, you can
also use it to perform other templating tasks, e.g. generating emails:

    post '/some/route' => sub {
        if (...) {
            email {
                to      => 'someone@example.com',
                from    => 'foo@example.com',
                subject => 'Hello there',
                msg     => template('emails/foo', { name => body_parameters->get('name') }),
            };

            return template 'message_sent';
        } else {
            return template 'error';
        }
    };

Compatibility notice: C<template> was changed in version 1.3090 to
immediately interrupt execution of a route handler and return the content,
as it's typically used at the end of a route handler to return content.
However, this caused issues for some people who were using C<template> to
generate emails etc, rather than accessing the template engine directly, so
this change has been reverted in 1.3091.

The first parameter should be a template available in the views directory,
the second one (optional) is a hashref of tokens to interpolate, and the
third (again optional) is a hashref of options.

For example, to disable the layout for a specific request:

    get '/' => sub {
        template 'index', {}, { layout => undef };
    };

Or to request a specific layout, of course:

    get '/user' => sub {
        template 'user', {}, { layout => 'user' };
    };

Some tokens are automatically added to your template (C<perl_version>,
C<dancer_version>, C<settings>, C<request>, C<vars> and, if you
have sessions enabled, C<session>). Check L<Default Template
Variables|Dancer2::Manual/Default-Template-Variables>
for further details.

=head2 to_app

Returns the PSGI coderef for the current (and only the current) application.

You can call it as a method on the class or as a DSL:

    my $app = MyApp->to_app;

    # or

    my $app = to_app;

There is a
L<Dancer Advent Calendar article|http://advent.perldancer.org/2014/9> covering
this keyword and its usage further.

=head2 to_dumper ($structure)

Serializes a structure with Data::Dumper.

Calling this function will B<not> trigger the serialization's hooks.

=head2 to_json ($structure, \%options)

Serializes a structure to JSON. You should probably use C<encode_json> instead
which handles encoding the result for you.

=head2 to_yaml ($structure)

Serializes a structure to YAML.

Calling this function will B<not> trigger the serialization's hooks.

=head2 true

Constant that returns a true value (1).

=head2 upload

Provides access to file uploads. Any uploaded file is accessible as a
L<Dancer2::Core::Request::Upload> object. You can access all parsed uploads
via:

    post '/some/route' => sub {
        my $file = upload('file_input_foo');
        # $file is a Dancer2::Core::Request::Upload object
    };

If you named multiple inputs of type "file" with the same name, the C<upload>
keyword would return an Array of L<Dancer2::Core::Request::Upload> objects:

    post '/some/route' => sub {
        my ($file1, $file2) = upload('files_input');
        # $file1 and $file2 are Dancer2::Core::Request::Upload objects
    };

You can also access the raw hashref of parsed uploads via the current
C<request> object:

    post '/some/route' => sub {
        my $all_uploads = request->uploads;
        # $all_uploads->{'file_input_foo'} is a Dancer2::Core::Request::Upload object
        # $all_uploads->{'files_input'} is an arrayref of Dancer2::Core::Request::Upload objects
    };

Note that you can also access the filename of the upload received via the
C<body_parameters> keyword:

    post '/some/route' => sub {
        # body_parameters->get('files_input') is the filename of the file uploaded
    };

See L<Dancer2::Core::Request::Upload> for details about the interface provided.

=head2 uri_for

Returns a fully-qualified URI for the given path:

    get '/' => sub {
        redirect uri_for('/path');
        # can be something like: http://localhost:5000/path
    };

Query string parameters can be provided by passing a hashref as a second param:

    uri_for('/path', { foo => 'bar' });
    # would return e.g. http://localhost:5000/path?foo=bar

By default, the parameters will be URL encoded:

    uri_for('/path', { foo => 'hope;faith' });
    # would return http://localhost:5000/path?foo=hope%3Bfaith

If desired (for example, if you've already encoded your query
parameters and you want to prevent double encoding) you can disable
URL encoding via a third parameter:

    uri_for('/path', { foo => 'qux%3Dquo' }, 1);
    # would return http://localhost:5000/path?foo=qux%3Dquo

=head2 uri_for_route

An enhanced version of C<uri_for> that utilizes routes' names.

    get 'view_entry' => '/entry/view/:id' => sub {...};

Now that the route has a name we can use C<uri_for_route> to
create a URI for it:

    my $path = uri_for_route(
        'view_entry',
        { 'id'  => 3 },
        { 'foo' => 'bar' },
    );

    # (assuming it's run on a local server in HTTP port 5000)
    # $path = 'http://localhost:5000/entry/view/3?foo=bar'

This works for every HTTP method, except C<HEAD> (which is
effectively a C<GET>).

It can also be used in templates:

    <!-- some_template.tt -->
    [% request.uri_for_route( 'my_route_name', { 'foo' => 'bar' }, { 'id' => 4 } ) %]

There are multiple arguments options:

=over 4

=item * Route parameters

The first argument controls the route parameters:

    get 'test' => '/:foo/:bar' => sub {1};
    # ...
    $path = uri_for_route( 'test', { 'foo' => 'hello', 'bar' => 'world' } );
    # $path = http://localhost:5000/hello/world

=item * Splat route parameters

If you provide an arrayref instead of hashref, it will assume on
these being splat and megasplat args:

    get 'test' => '/*/*/**' => sub {1};
    # ...
    $path = uri_for_route(
        'test',
        [ 'hello', 'world', [ 'myhello', 'myworld' ],
    );
    # $path = http://localhost:5000/hello/world/myhello/myworld

=item * Mixed route parameters

If you have a route that includes both, the splat and megasplat
arguments need to be under the C<splat> key:

    patch 'test' => '/*/:id/*/:foo/*' => sub {1};
    # ...
    $path = uri_for_route(
        'test',
        {
            'id'    => 4,
            'foo  ' => 'bar',
            'splat' => [ 'hello', 'world' ],
        }
    );
    # $path = http://localhost:5000/hello/4/world/bar

=item * Query parameters

If you want to create a path the query parameters, use the
second argument:

    get 'index'       => '/:foo' => sub {1};
    get 'update_form' => '/update' => sub {1};

    # ...

    $path = uri_for_route(
        'index',
        { 'foo' => 'bar' },
        { 'id'  => 1 },
    );
    # $path = http://localhost:5000/bar?id=1

    $path = uri_for_route( 'update_form', {}, { 'id' => 2 } );
    # $path = http://localhost:5000/update?id=2

(Technically, only C<GET> requests should include query parameters, but
C<uri_for_route> does not enforce this.)

=item * Disable URI escaping

The final parameter determines whether the URI will be URI-escaped or not:

    get 'show_entry' => '/view/:str_id' => sub {1};
    # ...
    $path = uri_for_route(
        'show_entry',
        { 'str_id' => '<javascript>...' },
        {},
    );
    # $path = http://localhost/view/%3Cjavascript%3E...

This is useful when your ID is not HTML-safe and might include HTML
tags and Javascript code or include characters that interfere with the
URI request string (like a forward slash).

This is on by default, but you can disable it by setting this flag:

    get 'show_entry' => '/view/:str_id' => sub {1};
    # ...
    $path = uri_for_route(
        'show_entry',
        { 'str_id' => '<javascript>...' },
        {},
        1,
    );
    # $path = http://localhost/view/<javascript>...

=back

=head2 var

Provides an accessor for variables shared between hooks and route
handlers. Given a key/value pair, it sets a variable:

    hook before => sub {
        var foo => 42;
    };

Later, route handlers and other hooks will be able to read that variable:

    get '/path' => sub {
        my $foo = var 'foo';
        ...
    };

=head2 vars

Returns the hashref of all shared variables set during the hook/route
chain with the C<var> keyword:

    get '/path' => sub {
        if (vars->{foo} eq 42) {
            ...
        }
    };

=head2 warning

Logs a warning message through the current logger engine:

    warning "This is a warning";

See L<Dancer2::Core::Role::Logger> for details on how to configure where log
messages go.

=head1 AUTHOR

Dancer Core Developers

=head1 COPYRIGHT AND LICENSE

This software is copyright (c) 2023 by Alexis Sukrieh.

This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.

=cut