Debian Codegraph @

lib/Dancer2/Core/Request.pm

raw
1 package Dancer2::Core::Request;
2 # ABSTRACT: Interface for accessing incoming requests
3 $Dancer2::Core::Request::VERSION = '2.2.2';
4 use strict;
5 use warnings;
6 use parent 'Plack::Request';
7
8 use Carp;
9 use Encode qw(decode FB_CROAK LEAVE_SRC);
10 use URI;
11 use URI::Escape;
12 use Safe::Isa;
13 use Hash::MultiValue;
14 use Ref::Util qw< is_ref is_arrayref is_hashref is_coderef >;
15
16 use Dancer2::Core::Types;
17 use Dancer2::Core::Request::Upload;
18 use Dancer2::Core::Cookie;
19
20 # add an attribute for each HTTP_* variables
21 # (HOST is managed manually)
22 my @http_env_keys = (qw/
23 accept_charset
24 accept_encoding
25 accept_language
26 connection
27 keep_alive
28 x_requested_with
29 /);
30
31 # apparently you can't eval core functions
32 sub accept { $_[0]->env->{'HTTP_ACCEPT'} }
33
34 eval << "_EVAL" or die $@ for @http_env_keys; ## no critic
35 sub $_ { \$_[0]->env->{ 'HTTP_' . ( uc "$_" ) } }
36 1;
37 _EVAL
38
39 eval {
40 require Unicode::UTF8;
41 no warnings qw<redefine once>;
42 *__decode = sub { Unicode::UTF8::decode_utf8($_[0]) };
43 *__valid = sub { Unicode::UTF8::valid_utf8($_[0]) };
44 1;
45 } or do {
46 no warnings qw<redefine once>;
47 *__decode = sub { decode( 'UTF-8', $_[0] ) };
48 *__valid = sub {
49 eval { decode( 'UTF-8', $_[0], FB_CROAK | LEAVE_SRC ); 1 };
50 };
51 };
52
53 # check presence of XS module to speedup request
54 our $XS_URL_DECODE = eval { require URL::Encode::XS; 1; };
55 our $XS_PARSE_QUERY_STRING = eval { require CGI::Deurl::XS; 1; };
56 our $XS_HTTP_COOKIES = eval { require HTTP::XSCookies; 1; };
57
58 our $_id = 0;
59
60 # self->new( env => {}, serializer => $s, is_behind_proxy => 0|1 )
61 sub new {
62 my ( $class, @args ) = @_;
63
64 # even sized list
65 @args % 2 == 0
66 or croak 'Must provide even sized list';
67
68 my %opts = @args;
69 my $env = $opts{'env'};
70
71 my $self = $class->SUPER::new($env);
72
73 if ( my $s = $opts{'serializer'} ) {
74 $s->$_does('Dancer2::Core::Role::Serializer')
75 or croak 'Serializer provided not a Serializer object';
76
77 $self->{'serializer'} = $s;
78 }
79
80 # additionally supported attributes
81 $self->{'id'} = ++$_id;
82 $self->{'vars'} = {};
83 $self->{'is_behind_proxy'} = !!$opts{'is_behind_proxy'};
84 $self->{'uri_for_route'} = $opts{'uri_for_route'};
85
86 $opts{'body_params'}
87 and $self->{'_body_params'} = $opts{'body_params'};
88 $self->{'_strict_utf8'} = !!$opts{'strict_utf8'};
89
90 # Deserialize/parse body for HMV
91 $self->data;
92 $self->_build_uploads();
93
94 return $self;
95 }
96
97 # a buffer for per-request variables
98 sub vars { $_[0]->{'vars'} }
99
100 sub var {
101 my $self = shift;
102 @_ == 2
103 ? $self->vars->{ $_[0] } = $_[1]
104 : $self->vars->{ $_[0] };
105 }
106
107 # I don't like this. I know send_file uses this and I wonder
108 # if we can remove it.
109 # -- Sawyer
110 sub set_path_info { $_[0]->env->{'PATH_INFO'} = $_[1] }
111
112 # XXX: incompatible with Plack::Request
113 sub body { $_[0]->raw_body }
114
115 sub id { $_id }
116
117 # Private 'read-only' attributes for request params. See the params()
118 # method for the public interface.
119 #
120 # _body_params, _query_params and _route_params have setter methods that
121 # decode byte string to characters before setting; If you know you have
122 # decoded (character) params, such as output from a deserializer, you can
123 # set these directly in the request object hash to avoid the decode op.
124 sub _params { $_[0]->{'_params'} ||= $_[0]->_build_params }
125
126 sub _has_params { defined $_[0]->{'_params'} }
127
128 sub _body_params { $_[0]->{'_body_params'} ||= $_[0]->body_parameters->as_hashref_mixed }
129
130 sub _query_params { $_[0]->{'_query_params'} }
131
132 sub _set_query_params {
133 my ( $self, $params ) = @_;
134 $self->{_query_params} = $self->_decode( $params, 'query parameters' );
135 }
136
137 sub _route_params { $_[0]->{'_route_params'} ||= {} }
138
139 sub _set_route_params {
140 my ( $self, $params ) = @_;
141 $self->{_route_params} = $self->_decode( $params, 'route parameters' );
142 $self->_build_params();
143 }
144
145 # XXX: incompatible with Plack::Request
146 sub uploads { $_[0]->{'uploads'} }
147
148 sub is_behind_proxy { $_[0]->{'is_behind_proxy'} || 0 }
149
150 sub host {
151 my ($self) = @_;
152
153 if ( $self->is_behind_proxy and exists $self->env->{'HTTP_X_FORWARDED_HOST'} ) {
154 my @hosts = split /\s*,\s*/, $self->env->{'HTTP_X_FORWARDED_HOST'}, 2;
155 return $hosts[0];
156 } else {
157 return $self->env->{'HTTP_HOST'};
158 }
159 }
160
161 # aliases, kept for backward compat
162 sub agent { shift->user_agent }
163 sub remote_address { shift->address }
164 sub forwarded_for_address { shift->env->{'HTTP_X_FORWARDED_FOR'} }
165 sub forwarded_host { shift->env->{'HTTP_X_FORWARDED_HOST'} }
166
167 # there are two options
168 sub forwarded_protocol {
169 $_[0]->env->{'HTTP_X_FORWARDED_PROTO'} ||
170 $_[0]->env->{'HTTP_X_FORWARDED_PROTOCOL'} ||
171 $_[0]->env->{'HTTP_FORWARDED_PROTO'}
172 }
173
174 sub scheme {
175 my ($self) = @_;
176 my $scheme = $self->is_behind_proxy
177 ? $self->forwarded_protocol
178 : '';
179
180 return $scheme || $self->env->{'psgi.url_scheme'};
181 }
182
183 sub serializer { $_[0]->{'serializer'} }
184
185 sub data { $_[0]->{'data'} ||= $_[0]->deserialize() }
186
187 sub deserialize {
188 my $self = shift;
189
190 # don't attempt to deserialize if the form is 'multipart/form-data'
191 if (
192 $self->content_type
193 && $self->content_type =~ /^multipart\/form-data/i
194 ) {
195 return;
196 }
197
198
199 my $serializer = $self->serializer
200 or return;
201
202 # The latest draft of the RFC does not forbid DELETE to have content,
203 # rather the behaviour is undefined. Take the most lenient route and
204 # deserialize any content on delete as well.
205 return
206 unless grep { $self->method eq $_ } qw/ PUT POST PATCH DELETE /;
207
208 # try to deserialize
209 my $body = $self->body;
210
211 $body && length $body > 0
212 or return;
213
214 # Catch serializer fails - which is tricky as Role::Serializer
215 # wraps the deserializaion in an eval and returns undef.
216 # We want to generate a 500 error on serialization fail (Ref #794)
217 # to achieve that, override the log callback so we can catch a signal
218 # that it failed. This is messy (messes with serializer internals), but
219 # "works".
220 my $serializer_fail;
221 my $serializer_log_cb = $serializer->log_cb;
222 local $serializer->{log_cb} = sub {
223 $serializer_fail = $_[1];
224 $serializer_log_cb->(@_);
225 };
226 # work-around to resolve a chicken-and-egg issue when instantiating a
227 # request object; the serializer needs that request object to deserialize
228 # the body params.
229 Scalar::Util::weaken( my $request = $self );
230 $self->serializer->has_request || $self->serializer->set_request($request);
231 my $data = $serializer->deserialize($body);
232 die $serializer_fail if $serializer_fail;
233
234 # Set _body_params directly rather than using the setter. Deserializiation
235 # returns characters and skipping the decode op in the setter ensures
236 # that numerical data "stays" numerical; decoding an SV that is an IV
237 # converts that to a PVIV. Some serializers are picky (JSON)..
238 $self->{_body_params} = $data;
239
240 # Set body parameters (decoded HMV)
241 $self->{'body_parameters'} =
242 Hash::MultiValue->from_mixed( is_hashref($data) ? %$data : () );
243
244 return $data;
245 }
246
247 sub uri { $_[0]->request_uri }
248
249 sub is_head { $_[0]->method eq 'HEAD' }
250 sub is_post { $_[0]->method eq 'POST' }
251 sub is_get { $_[0]->method eq 'GET' }
252 sub is_put { $_[0]->method eq 'PUT' }
253 sub is_delete { $_[0]->method eq 'DELETE' }
254 sub is_patch { $_[0]->method eq 'PATCH' }
255 sub is_options { $_[0]->method eq 'OPTIONS' }
256
257 # public interface compat with CGI.pm objects
258 sub request_method { $_[0]->method }
259 sub input_handle { $_[0]->env->{'psgi.input'} }
260
261 sub to_string {
262 my ($self) = @_;
263 return "[#" . $self->id . "] " . $self->method . " " . $self->path;
264 }
265
266 sub base {
267 my $self = shift;
268 my $uri = $self->_common_uri;
269
270 return $uri->canonical;
271 }
272
273 sub _common_uri {
274 my $self = shift;
275
276 my $path = $self->env->{SCRIPT_NAME};
277 my $port = $self->env->{SERVER_PORT};
278 my $server = $self->env->{SERVER_NAME};
279 my $host = $self->host;
280 my $scheme = $self->scheme;
281
282 my $uri = URI->new;
283 $uri->scheme($scheme);
284 $uri->authority( $host || "$server:$port" );
285 $uri->path( $path || '/' );
286
287 return $uri;
288 }
289
290 sub uri_base {
291 my $self = shift;
292 my $uri = $self->_common_uri;
293 my $canon = $uri->canonical;
294
295 if ( $uri->path eq '/' ) {
296 $canon =~ s{/$}{};
297 }
298
299 return $canon;
300 }
301
302 sub path {
303 my $self = shift;
304 my $path = $self->env->{PATH_INFO} || '/';
305 return $self->_decode_bytes( $path, 'PATH_INFO' );
306 }
307
308 sub dispatch_path {
309 Carp::croak q{DEPRECATED: request->dispatch_path. Please use request->path instead};
310 }
311
312 sub uri_for {
313 my ( $self, $part, $params, $dont_escape ) = @_;
314
315 $part ||= '';
316 my $uri = $self->base;
317
318 # Make sure there's exactly one slash between the base and the new part
319 my $base = $uri->path;
320 $base =~ s|/$||;
321 $part =~ s|^/||;
322 $uri->path("$base/$part");
323
324 $uri->query_form($params) if $params;
325
326 return $dont_escape
327 ? uri_unescape( ${ $uri->canonical } )
328 : ${ $uri->canonical };
329 }
330
331 sub uri_for_route {
332 my ( $self, @args ) = @_;
333
334 is_coderef( $self->{'uri_for_route'} )
335 or die 'uri_for_route called on a request instance without it';
336
337 return $self->{'uri_for_route'}->(@_);
338 }
339
340 sub params {
341 my ( $self, $source ) = @_;
342
343 return %{ $self->_params } if wantarray && @_ == 1;
344 return $self->_params if @_ == 1;
345
346 if ( $source eq 'query' ) {
347 return %{ $self->_query_params || {} } if wantarray;
348 return $self->_query_params;
349 }
350 elsif ( $source eq 'body' ) {
351 return %{ $self->_body_params || {} } if wantarray;
352 return $self->_body_params;
353 }
354 if ( $source eq 'route' ) {
355 return %{ $self->_route_params } if wantarray;
356 return $self->_route_params;
357 }
358 else {
359 croak "Unknown source params \"$source\".";
360 }
361 }
362
363 sub query_parameters {
364 my $self = shift;
365 $self->{'query_parameters'} ||= do {
366 if ($XS_PARSE_QUERY_STRING) {
367 my $query = $self->_decode(CGI::Deurl::XS::parse_query_string(
368 $self->env->{'QUERY_STRING'}
369 ), 'query parameters');
370
371 Hash::MultiValue->new(
372 map {;
373 my $key = $_;
374 is_arrayref( $query->{$key} )
375 ? ( map +( $key => $_ ), @{ $query->{$key} } )
376 : ( $key => $query->{$key} )
377 } keys %{$query}
378 );
379 } else {
380 # defer to Plack::Request
381 $self->_decode($self->SUPER::query_parameters, 'query parameters');
382 }
383 };
384 }
385
386 # this will be filled once the route is matched
387 sub route_parameters { $_[0]->{'route_parameters'} ||= Hash::MultiValue->new }
388
389 sub _set_route_parameters {
390 my ( $self, $params ) = @_;
391 # remove reserved splat parameter name
392 # you should access splat parameters using splat() keyword
393 delete @{$params}{qw<splat captures>};
394 $self->{'route_parameters'} = Hash::MultiValue->from_mixed(
395 %{ $self->_decode( $params, 'route parameters' ) }
396 );
397 }
398
399 sub body_parameters {
400 my $self = shift;
401 # defer to (the overridden) Plack::Request->body_parameters
402 $self->{'body_parameters'} ||= $self->_decode(
403 $self->SUPER::body_parameters(),
404 'body parameters',
405 );
406 }
407
408 sub parameters {
409 my ( $self, $type ) = @_;
410
411 # handle a specific case
412 if ($type) {
413 my $attr = "${type}_parameters";
414 return $self->$attr;
415 }
416
417 # merge together the *decoded* parameters
418 $self->{'merged_parameters'} ||= do {
419 my $query = $self->query_parameters;
420 my $body = $self->body_parameters;
421 my $route = $self->route_parameters; # not in Plack::Request
422 Hash::MultiValue->new( map $_->flatten, $query, $body, $route );
423 };
424 }
425
426 sub captures { shift->params->{captures} || {} }
427
428 sub splat { @{ shift->params->{splat} || [] } }
429
430 # XXX: incompatible with Plack::Request
431 sub param { shift->params->{ $_[0] } }
432
433 sub _decode {
434 my ( $self, $h, $context ) = @_;
435 return if not defined $h;
436
437 if ( !is_ref($h) && !utf8::is_utf8($h) ) {
438 return $self->_decode_bytes( $h, $context );
439 }
440 elsif ( ref($h) eq 'Hash::MultiValue' ) {
441 return Hash::MultiValue->from_mixed(
442 $self->_decode( $h->as_hashref_mixed, $context )
443 );
444 }
445 elsif ( is_hashref($h) ) {
446 return { map scalar $self->_decode( $_, $context ), %{$h} };
447 }
448 elsif ( is_arrayref($h) ) {
449 return [ map $self->_decode( $_, $context ), @{$h} ];
450 }
451
452 return $h;
453 }
454
455 sub _decode_bytes {
456 my ( $self, $bytes, $context ) = @_;
457
458 # If PSGI already gave us characters, avoid re-decoding.
459 return $bytes if utf8::is_utf8($bytes);
460 return $bytes if $bytes !~ /[\x80-\xFF]/;
461
462 return __decode($bytes) if __valid($bytes);
463 return $self->_invalid_utf8( $bytes, $context );
464 }
465
466 sub _invalid_utf8 {
467 my ( $self, $bytes, $context ) = @_;
468 my $strict = $self->{_strict_utf8};
469 my $where = $context || 'input';
470 my $msg = "Invalid UTF-8 in $where";
471
472 $strict
473 and Carp::croak($msg);
474
475 if ( my $logger = $self->env->{'psgix.logger'} ) {
476 $logger->({
477 level => 'warning',
478 message => "$msg; leaving bytes unchanged",
479 });
480 } else {
481 Carp::carp("$msg; leaving bytes unchanged");
482 }
483
484 return $bytes;
485 }
486
487 sub is_ajax {
488 my $self = shift;
489
490 return 0 unless defined $self->headers;
491 return 0 unless defined $self->header('X-Requested-With');
492 return 0 if $self->header('X-Requested-With') ne 'XMLHttpRequest';
493 return 1;
494 }
495
496 # XXX incompatible with Plack::Request
497 # context-aware accessor for uploads
498 sub upload {
499 my ( $self, $name ) = @_;
500 my $res = $self->{uploads}{$name};
501
502 return $res unless wantarray;
503 return () unless defined $res;
504 return ( is_arrayref($res) ) ? @$res : $res;
505 }
506
507 sub _build_params {
508 my ($self) = @_;
509
510 # params may have been populated by before filters
511 # _before_ we get there, so we have to save it first
512 my $previous = $self->_has_params ? $self->_params : {};
513
514 # now parse environment params...
515 my $get_params = $self->_parse_get_params();
516
517 # and merge everything
518 $self->{_params} = {
519 map +( is_hashref($_) ? %{$_} : () ),
520 $previous,
521 $get_params,
522 $self->_body_params,
523 $self->_route_params,
524 };
525
526 }
527
528 sub _url_decode {
529 my ( $self, $encoded ) = @_;
530 return URL::Encode::XS::url_decode($encoded) if $XS_URL_DECODE;
531 my $clean = $encoded;
532 $clean =~ tr/\+/ /;
533 $clean =~ s/%([a-fA-F0-9]{2})/pack "H2", $1/eg;
534 return $clean;
535 }
536
537 sub _parse_get_params {
538 my ($self) = @_;
539 return $self->_query_params if defined $self->{_query_params};
540
541 my $query_params = {};
542
543 my $source = $self->env->{QUERY_STRING};
544 return if !defined $source || $source eq '';
545
546 if ($XS_PARSE_QUERY_STRING) {
547 $self->_set_query_params(
548 CGI::Deurl::XS::parse_query_string($source) || {}
549 );
550 return $self->_query_params;
551 }
552
553 foreach my $token ( split /[&;]/, $source ) {
554 my ( $key, $val ) = split( /=/, $token );
555 next unless defined $key;
556 $val = ( defined $val ) ? $val : '';
557 $key = $self->_url_decode($key);
558 $val = $self->_url_decode($val);
559
560 # looking for multi-value params
561 if ( exists $query_params->{$key} ) {
562 my $prev_val = $query_params->{$key};
563 if ( is_arrayref($prev_val) ) {
564 push @{ $query_params->{$key} }, $val;
565 }
566 else {
567 $query_params->{$key} = [ $prev_val, $val ];
568 }
569 }
570
571 # simple value param (first time we see it)
572 else {
573 $query_params->{$key} = $val;
574 }
575 }
576 $self->_set_query_params( $query_params );
577 return $self->_query_params;
578 }
579
580 sub _build_uploads {
581 my ($self) = @_;
582
583 # parse body and build body params
584 my $body_params = $self->_body_params;
585
586 my $uploads = $self->SUPER::uploads;
587 my %uploads;
588
589 for my $name ( keys %$uploads ) {
590 my @uploads = map Dancer2::Core::Request::Upload->new(
591 # For back-compatibility, we use a HashRef of headers
592 headers => {@{$_->{headers}->psgi_flatten_without_sort}},
593 tempname => $_->{tempname},
594 size => $_->{size},
595 filename => $self->_decode( $_->{filename}, 'upload filename' ),
596 ), $uploads->get_all($name);
597
598 $uploads{$name} = @uploads > 1 ? \@uploads : $uploads[0];
599
600 # support access to the filename as a normal param
601 my @filenames = map $_->{'filename'}, @uploads;
602 $self->{_body_params}{$name} =
603 @filenames > 1 ? \@filenames : $filenames[0];
604 }
605
606 $self->{uploads} = \%uploads;
607 }
608
609 # XXX: incompatible with Plack::Request
610 sub cookies { $_[0]->{'cookies'} ||= $_[0]->_build_cookies }
611
612 sub _build_cookies {
613 my $self = shift;
614 my $cookies = {};
615
616 my $http_cookie = $self->header('Cookie');
617 return $cookies unless defined $http_cookie; # nothing to do
618
619 if ( $XS_HTTP_COOKIES ) {
620 $cookies = HTTP::XSCookies::crush_cookie($http_cookie);
621 }
622 else {
623 # handle via Plack::Request
624 $cookies = $self->SUPER::cookies();
625 }
626
627 # convert to objects
628 while (my ($name, $value) = each %{$cookies}) {
629 $cookies->{$name} = Dancer2::Core::Cookie->new(
630 name => $name,
631 # HTTP::XSCookies v0.17+ will do the split and return an arrayref
632 value => is_arrayref($value) ? $value : [split '&', $value ]
633 );
634 }
635 return $cookies;
636 }
637
638 # poor man's clone
639 sub _shallow_clone {
640 my ($self, $params, $options) = @_;
641
642 # shallow clone $env; we don't want to alter the existing one
643 # in $self, then merge any overridden values
644 my $env = { %{ $self->env }, %{ $options || {} } };
645
646 my $new_request = __PACKAGE__->new(
647 env => $env,
648 body_params => {},
649 );
650
651 # Clone and merge query params
652 my $new_params = $self->params;
653 $new_request->{_query_params} = { %{ $self->{_query_params} || {} } };
654 $new_request->{_strict_utf8} = $self->{_strict_utf8};
655 $new_request->{query_parameters} = $self->query_parameters->clone;
656 for my $key ( keys %{ $params || {} } ) {
657 my $value = $params->{$key};
658 $new_params->{$key} = $value;
659 $new_request->{_query_params}->{$key} = $value;
660 $new_request->{query_parameters}->add( $key => $value );
661 }
662
663 # Copy params (these are already decoded)
664 $new_request->{_params} = $new_params;
665 $new_request->{_body_params} = $self->{_body_params};
666 $new_request->{_route_params} = $self->{_route_params};
667 $new_request->{headers} = $self->headers;
668
669 # Copy remaining settings
670 $new_request->{is_behind_proxy} = $self->{is_behind_proxy};
671 $new_request->{vars} = $self->{vars};
672
673 # Clone any existing decoded & cached body params. (GH#1116 GH#1269)
674 $new_request->{'body_parameters'} = $self->body_parameters->clone;
675
676 # Delete merged HMV parameters, allowing them to be reconstructed on first use.
677 delete $new_request->{'merged_parameters'};
678
679 return $new_request;
680 }
681
682
683 sub _set_route {
684 my ( $self, $route ) = @_;
685 $self->{'route'} = $route;
686 }
687
688 sub route { $_[0]->{'route'} }
689
690 sub body_data {
691 my $self = shift;
692 return $self->data if $self->serializer;
693 $self->_body_params;
694 return $self->{_body_params} if keys %{ $self->{_body_params} };
695 return $self->body;
696 }
697
698 1;
699
700 __END__
701
702 =pod
703
704 =encoding UTF-8
705
706 =head1 NAME
707
708 Dancer2::Core::Request - Interface for accessing incoming requests
709
710 =head1 VERSION
711
712 version 2.2.2
713
714 =head1 SYNOPSIS
715
716 In a route handler, the current request object can be accessed by the
717 C<request> keyword:
718
719 get '/foo' => sub {
720 request->params; # request, params parsed as a hash ref
721 request->body; # returns the request body, unparsed
722 request->path; # the path requested by the client
723 # ...
724 };
725
726 =head1 DESCRIPTION
727
728 An object representing a Dancer2 request. It aims to provide a proper
729 interface to anything you might need from a web request.
730
731 =head1 METHODS
732
733 =head2 address
734
735 Return the IP address of the client.
736
737 =head2 base
738
739 Returns an absolute URI for the base of the application. Returns a L<URI>
740 object (which stringifies to the URL, as you'd expect).
741
742 =head2 body_parameters
743
744 Returns a L<Hash::MultiValue> object representing the POST parameters.
745
746 =head2 body
747
748 Return the raw body of the request, unparsed.
749
750 If you need to access the body of the request, you have to use this accessor and
751 should not try to read C<psgi.input> by hand. C<Dancer2::Core::Request>
752 already did it for you and kept the raw body untouched in there.
753
754 =head2 body_data
755
756 Returns the body of the request in data form, making it possible to distinguish
757 between C<body_parameters>, a representation of the request parameters
758 (L<Hash::MultiValue>) and other forms of content.
759
760 If a serializer is set, this is the deserialized request body. Otherwise this is
761 the decoded body parameters (if any), or the body content itself.
762
763 =head2 content
764
765 Returns the undecoded byte string POST body.
766
767 =head2 cookies
768
769 Returns a reference to a hash containing cookies, where the keys are the names of the
770 cookies and values are L<Dancer2::Core::Cookie> objects.
771
772 =head2 data
773
774 If the application has a serializer and if the request has serialized
775 content, returns the deserialized structure as a hashref.
776
777 =head2 dispatch_path
778
779 Alias for L<path>. Deprecated.
780
781 =head2 env
782
783 Return the current PSGI environment hash reference.
784
785 =head2 header($name)
786
787 Return the value of the given header, if present. If the header has multiple
788 values, returns an the list of values if called in list context, the first one
789 in scalar.
790
791 =head2 headers
792
793 Returns either an L<HTTP::Headers> or an L<HTTP::Headers::Fast> object
794 representing the headers.
795
796 =head2 id
797
798 The ID of the request. This allows you to trace a specific request in loggers,
799 per the string created using C<to_string>.
800
801 The ID of the request is essentially the number of requests run in the current
802 class.
803
804 =head2 input
805
806 Alias to C<input_handle> method below.
807
808 =head2 input_handle
809
810 Alias to the PSGI input handle (C<< request->env->{'psgi.input'} >>)
811
812 =head2 is_ajax
813
814 Return true if the value of the header C<X-Requested-With> is
815 C<XMLHttpRequest>.
816
817 =head2 is_delete
818
819 Return true if the method requested by the client is 'DELETE'
820
821 =head2 is_get
822
823 Return true if the method requested by the client is 'GET'
824
825 =head2 is_head
826
827 Return true if the method requested by the client is 'HEAD'
828
829 =head2 is_post
830
831 Return true if the method requested by the client is 'POST'
832
833 =head2 is_put
834
835 Return true if the method requested by the client is 'PUT'
836
837 =head2 is_options
838
839 Return true if the method requested by the client is 'OPTIONS'
840
841 =head2 logger
842
843 Returns the C<psgix.logger> code reference, if exists.
844
845 =head2 method
846
847 Return the HTTP method used by the client to access the application.
848
849 While this method returns the method string as provided by the environment, it's
850 better to use one of the following boolean accessors if you want to inspect the
851 requested method.
852
853 =head2 new
854
855 The constructor of the class, used internally by Dancer2's core to create request
856 objects.
857
858 It uses the environment hash table given to build the request object:
859
860 Dancer2::Core::Request->new( env => $env );
861
862 There are two additional parameters for instantiation:
863
864 =over 4
865
866 =item * serializer
867
868 A serializer object to work with when reading the request body.
869
870 =item * body_params
871
872 Provide body parameters.
873
874 Used internally when we need to avoid parsing the body again.
875
876 =back
877
878 =head2 param($key)
879
880 Calls the C<params> method below and fetches the key provided.
881
882 =head2 params($source)
883
884 Called in scalar context, returns a hashref of params, either from the specified
885 source (see below for more info on that) or merging all sources.
886
887 So, you can use, for instance:
888
889 my $foo = params->{foo}
890
891 If called in list context, returns a list of key and value pairs, so you could use:
892
893 my %allparams = params;
894
895 Parameters are merged in the following order: query, body, route - i.e. route
896 parameters have the highest priority:
897
898 POST /hello/Ruth?name=Quentin
899
900 name=Bobbie
901
902 post '/hello/:name' => sub {
903 return "Hello, " . route_parameters->get('name') . "!"; # returns Ruth
904 return "Hello, " . query_parameters->get('name') . "!"; # returns Quentin
905 return "Hello, " . body_parameters->get('name') . "!"; # returns Bobbie
906 return "Hello, " . param('name') . "!"; # returns Ruth
907 };
908
909 The L</query_parameters>, L</route_parameters>, and L</body_parameters> keywords
910 provide a L<Hash::MultiValue> result from the three different parameters.
911 We recommend using these rather than C<params>, because of the potential for
912 unintentional behaviour - consider the following request and route handler:
913
914 POST /artist/104/new-song
915
916 name=Careless Dancing
917
918 post '/artist/:id/new-song' => sub {
919 find_artist(param('id'))->create_song(params);
920 # oops! we just passed id into create_song,
921 # but we probably only intended to pass name
922 find_artist(param('id'))->create_song(body_parameters);
923 };
924
925 POST /artist/104/join-band
926
927 id=4
928 name=Dancing Misfits
929
930 post '/artist/:id/new-song' => sub {
931 find_artist(param('id'))->join_band(params);
932 # oops! we just passed an id of 104 into join_band,
933 # but we probably should have passed an id of 4
934 };
935
936 =head2 parameters
937
938 Returns a L<Hash::MultiValue> object with merged GET and POST parameters.
939
940 Parameters are merged in the following order: query, body, route - i.e. route
941 parameters have the highest priority - see L</params> for how this works, and
942 associated risks and alternatives.
943
944 =head2 path
945
946 The decoded path requested by the client, normalized. This is effectively
947 C<path_info> or a single forward C</>. Invalid UTF-8 is left as bytes in
948 lenient mode (with a warning), or throws an error in strict UTF-8 mode.
949
950 =head2 path_info
951
952 The raw requested path. This could be empty. Use C<path> instead.
953
954 =head2 port
955
956 Return the port of the server.
957
958 =head2 protocol
959
960 Return the protocol (I<HTTP/1.0> or I<HTTP/1.1>) used for the request.
961
962 =head2 query_parameters
963
964 Returns a L<Hash::MultiValue> parameters object.
965
966 =head2 query_string
967
968 Returns the portion of the request defining the query itself - this is
969 what comes after the C<?> in a URI.
970
971 =head2 raw_body
972
973 Alias to C<content> method.
974
975 =head2 remote_address
976
977 Alias for C<address> method.
978
979 =head2 remote_host
980
981 Return the remote host of the client. This only works with web servers configured
982 to do a reverse DNS lookup on the client's IP address.
983
984 =head2 request_method
985
986 Alias to the C<method> accessor, for backward-compatibility with C<CGI> interface.
987
988 =head2 request_uri
989
990 Return the raw, undecoded request URI path.
991
992 =head2 route
993
994 Return the L<route|Dancer2::Core::Route> which this request matched.
995
996 =head2 scheme
997
998 Return the scheme of the request
999
1000 =head2 script_name
1001
1002 Return script_name from the environment.
1003
1004 =head2 secure
1005
1006 Return true or false, indicating whether the connection is secure - this is
1007 effectively checking if the scheme is I<HTTPS> or not.
1008
1009 =head2 serializer
1010
1011 Returns the optional serializer object used to deserialize request parameters.
1012
1013 =head2 session
1014
1015 Returns the C<psgix.session> hash, if exists.
1016
1017 =head2 session_options
1018
1019 Returns the C<psgix.session.options> hash, if exists.
1020
1021 =head2 to_string
1022
1023 Return a string representing the request object (e.g., C<GET /some/path>).
1024
1025 =head2 upload($name)
1026
1027 Context-aware accessor for uploads. It's a wrapper around an access to the hash
1028 table provided by C<uploads()>. It looks at the calling context and returns a
1029 corresponding value.
1030
1031 If you have many file uploads under the same name, and call C<upload('name')> in
1032 an array context, the accessor will unroll the ARRAY ref for you:
1033
1034 my @uploads = request->upload('many_uploads'); # OK
1035
1036 Whereas with a manual access to the hash table, you'll end up with one element
1037 in C<@uploads>, being the arrayref:
1038
1039 my @uploads = request->uploads->{'many_uploads'};
1040 # $uploads[0]: ARRAY(0xXXXXX)
1041
1042 That is why this accessor should be used instead of a manual access to
1043 C<uploads>.
1044
1045 =head2 uploads
1046
1047 Returns a reference to a hash containing uploads. Values can be either a
1048 L<Dancer2::Core::Request::Upload> object, or an arrayref of
1049 L<Dancer2::Core::Request::Upload>
1050 objects.
1051
1052 You should probably use the C<upload($name)> accessor instead of manually accessing the
1053 C<uploads> hash table.
1054
1055 =head2 uri
1056
1057 An alias to C<request_uri>.
1058
1059 =head2 uri_base
1060
1061 Same thing as C<base> above, except it removes the last trailing slash in the
1062 path if it is the only path.
1063
1064 This means that if your base is I<http://myserver/>, C<uri_base> will return
1065 I<http://myserver> (notice no trailing slash). This is considered very useful
1066 when using templates to do the following thing:
1067
1068 <link rel="stylesheet" href="[% request.uri_base %]/css/style.css" />
1069
1070 =head2 uri_for(path, params)
1071
1072 Constructs a URI from the base and the passed path. If params (hashref) is
1073 supplied, these are added to the query string of the URI.
1074
1075 Thus, with the following base:
1076
1077 http://localhost:5000/foo
1078
1079 You get the following behavior:
1080
1081 my $uri = request->uri_for('/bar', { baz => 'baz' });
1082 print $uri; # http://localhost:5000/foo/bar?baz=baz
1083
1084 C<uri_for> returns a L<URI> object (which can stringify to the value).
1085
1086 =head2 uri_for_route(route_name, route_params, query_params, escape)
1087
1088 Constructs a URI from the base and the path of the specified route name.
1089
1090 Read more about it in the C<Dancer2::Manual::Keywords> document under
1091 C<uri_for_route>.
1092
1093 =head2 user
1094
1095 Return remote user if defined.
1096
1097 =head2 var
1098
1099 By-name interface to variables stored in this request object.
1100
1101 my $stored = $request->var('some_variable');
1102
1103 returns the value of 'some_variable', while
1104
1105 $request->var('some_variable' => 'value');
1106
1107 will set it.
1108
1109 =head2 vars
1110
1111 Access to the internal hash of variables:
1112
1113 my $value = $request->vars->{'my_key'};
1114
1115 You want to use C<var> above.
1116
1117 =head1 Common HTTP request headers
1118
1119 Commonly used client-supplied HTTP request headers are available through
1120 specific accessors:
1121
1122 =over 4
1123
1124 =item C<accept>
1125
1126 HTTP header: C<HTTP_ACCEPT>.
1127
1128 =item C<accept_charset>
1129
1130 HTTP header: C<HTTP_ACCEPT_CHARSET>.
1131
1132 =item C<accept_encoding>
1133
1134 HTTP header: C<HTTP_ACCEPT_ENCODING>.
1135
1136 =item C<accept_language>
1137
1138 HTTP header: C<HTTP_ACCEPT_LANGUAGE>.
1139
1140 =item C<agent>
1141
1142 Alias for C<user_agent>) below.
1143
1144 =item C<connection>
1145
1146 HTTP header: C<HTTP_CONNECTION>.
1147
1148 =item C<content_encoding>
1149
1150 HTTP header: C<HTTP_CONTENT_ENCODING>.
1151
1152 =item C<content_length>
1153
1154 HTTP header: C<HTTP_CONTENT_LENGTH>.
1155
1156 =item C<content_type>
1157
1158 HTTP header: C<HTTP_CONTENT_TYPE>.
1159
1160 =item C<forwarded_for_address>
1161
1162 HTTP header: C<HTTP_X_FORWARDED_FOR>.
1163
1164 =item C<forwarded_host>
1165
1166 HTTP header: C<HTTP_X_FORWARDED_HOST>.
1167
1168 =item C<forwarded_protocol>
1169
1170 One of either C<HTTP_X_FORWARDED_PROTOCOL>, C<HTTP_X_FORWARDED_PROTO>, or
1171 C<HTTP_FORWARDED_PROTO>.
1172
1173 =item C<host>
1174
1175 Checks whether we are behind a proxy using the C<behind_proxy>
1176 configuration option, and if so returns the first
1177 C<HTTP_X_FORWARDED_HOST>, since this is a comma separated list.
1178
1179 If you have not configured that you are behind a proxy, it returns HTTP
1180 header C<HTTP_HOST>.
1181
1182 =item C<keep_alive>
1183
1184 HTTP header: C<HTTP_KEEP_ALIVE>.
1185
1186 =item C<referer>
1187
1188 HTTP header: C<HTTP_REFERER>.
1189
1190 =item C<user_agent>
1191
1192 HTTP header: C<HTTP_USER_AGENT>.
1193
1194 =item C<x_requested_with>
1195
1196 HTTP header: C<HTTP_X_REQUESTED_WITH>.
1197
1198 =back
1199
1200 =head1 Fetching only params from a given source
1201
1202 If a required source isn't specified, a mixed hashref (or list of key value
1203 pairs, in list context) will be returned; this will contain params from all
1204 sources (route, query, body).
1205
1206 In practical terms, this means that if the param C<foo> is passed both on the
1207 querystring and in a POST body, you can only access one of them.
1208
1209 If you want to see only params from a given source, you can say so by passing
1210 the C<$source> param to C<params()>:
1211
1212 my %querystring_params = params('query');
1213 my %route_params = params('route');
1214 my %post_params = params('body');
1215
1216 If source equals C<route>, then only params parsed from the route pattern
1217 are returned.
1218
1219 If source equals C<query>, then only params parsed from the query string are
1220 returned.
1221
1222 If source equals C<body>, then only params sent in the request body will be
1223 returned.
1224
1225 If another value is given for C<$source>, then an exception is triggered.
1226
1227 =head1 EXTRA SPEED
1228
1229 If L<Dancer2::Core::Request> detects the following modules as installed,
1230 it will use them to speed things up:
1231
1232 =over 4
1233
1234 =item * L<URL::Encode::XS>
1235
1236 =item * L<CGI::Deurl::XS>
1237
1238 =back
1239
1240 =head1 AUTHOR
1241
1242 Dancer Core Developers
1243
1244 =head1 COPYRIGHT AND LICENSE
1245
1246 This software is copyright (c) 2026 by Alexis Sukrieh.
1247
1248 This is free software; you can redistribute it and/or modify it under
1249 the same terms as the Perl 5 programming language system itself.
1250
1251 =cut