Cataly...Request(3pm)

πŸ“¦
version 5.90132 Β· 6 versions
, in debian trixie, ubuntu resolute, ubuntu stonking

πŸ’– Catalyst::Request β€” the vibe check on ur client request πŸ’–

Cataly...Request(3pm) β€” User Contributed Perl Documentation β€” Cataly...Request(3pm)

okay so bestie, welcome to Catalyst::Request. it's the class that hands u all the tea about the current client request. grab a strawberry drink πŸ“ and let's go.


✨ NAME ✨

Catalyst::Request β€” provides information about the current client request. that's it, that's the whole job. it's giving "i know everything about the person knocking at ur door". πŸ’…


🌈 SYNOPSIS 🌈

here's every single thing u can call on $req, laid out exactly:

$req = $c->request;
$req->address eq "127.0.0.1";
$req->arguments;
$req->args;
$req->base;
$req->body;
$req->body_data;
$req->body_parameters;
$req->content_encoding;
$req->content_length;
$req->content_type;
$req->cookie;
$req->cookies;
$req->header;
$req->headers;
$req->hostname;
$req->input;
$req->query_keywords;
$req->match;
$req->method;
$req->param;
$req->parameters;
$req->params;
$req->path;
$req->protocol;
$req->query_parameters;
$req->read;
$req->referer;
$req->secure;
$req->captures;
$req->upload;
$req->uploads;
$req->uri;
$req->user;
$req->user_agent;
$req->env;

also go peek at Catalyst and Catalyst::Request::Upload when ur done here 🫢


πŸ¦‹ DESCRIPTION πŸ¦‹

so this is the Catalyst Request class, and it's literally the interface to all the data floating around in the current client request. the request object gets prepared by Catalyst::Engine, which means all the messy details of whatever engine implementation ur running get hidden away. u just get the pretty version. main character energy, honestly. πŸ‘‘


πŸ‘‘ METHODS πŸ‘‘

$req->address

Returns the IP address of the client. who's at the door? it tells u. πŸšͺ

$req->arguments

Returns a reference to an array containing the arguments.

print $c->request->arguments->[0];

so like, if ur action looked like this:

package MyApp::Controller::Foo;

sub moose : Local {
    ...
}

and the URI for the request was http://.../foo/moose/bah, then the string bah would be the first and only argument. iconic.

Arguments get automatically URI-unescaped for you, so u don't gotta do it urself. no cap. ✨

$req->args

Shortcut for arguments. same energy, fewer letters.

$req->base

Contains the URI base. this will always have a trailing slash. ⚠️ heads up tho: the URI scheme (like, http vs. https) has to be figured out through heuristics, so depending on ur server configuration it might be straight up incorrect. see $req->secure for more info on that.

if ur application was queried with the URI http://localhost:3000/some/path then base is http://localhost:3000/. slay.

$req->body

Returns the message body of the request, as returned by HTTP::Body: a string, unless Content-Type is application/x-www-form-urlencoded, text/xml, or multipart/form-data, in which case a File::Temp object is returned. plot twist 🫒

$req->body_data

Returns a Perl representation of body data that is not classic HTML form data, such as JSON, XML, etc. By default, Catalyst will parse incoming data of the type 'application/json' for POST, PUT, PATCH or DELETE methods, and return access to that data via this method.

u may define addition data_handlers via a global configuration setting. see Catalyst\DATA HANDLERS for more information. (yes bestie, that's a literal backslash in there, keep it.)

if the body is malformed in some way (like undefined, or content that doesn't match the content-type) we raise a Catalyst::Exception with the error text as the message. 🚨

if the body content type does not match an available data handler, this will also raise an exception. double 🚨

$req->body_parameters

Returns a reference to a hash containing body (POST) parameters. Values can be either a scalar or an arrayref containing scalars.

print $c->request->body_parameters->{field};
print $c->request->body_parameters->{field}->[0];

these are the parameters from the POST part of the request, if any.

NOTE If your POST is multipart, but contains non file upload parts (such as an line part with an alternative encoding or content type) we do our best to try and figure out how the value should be presented. If there's a specified character set we will use that to decode rather than the default encoding set by the application. However if there are complex headers and we cannot determine the correct way to extra a meaningful value from the upload, in this case any part like this will be represented as an instance of Catalyst::Request::PartData.

Patches and review of this part of the code welcomed. (they're literally asking, bestie, if u got the skills πŸ‘€)

$req->body_params

Shortcut for body_parameters.

$req->content_encoding

Shortcut for $req->headers->content_encoding.

$req->content_length

Shortcut for $req->headers->content_length.

$req->content_type

Shortcut for $req->headers->content_type.

A convenient method to access $req->cookies.

$cookie  = $c->request->cookie('name');
@cookies = $c->request->cookie;

$req->cookies

Returns a reference to a hash containing the cookies. πŸͺ (yes, actual cookies, not the fun kind, sorry)

print $c->request->cookies->{mycookie}->value;

the cookies in the hash are indexed by name, and the values are CGI::Simple::Cookie objects.

$req->header

Shortcut for $req->headers->header.

$req->headers

Returns an HTTP::Headers object containing the headers for the current request.

print $c->request->headers->header('X-Catalyst');

$req->hostname

Returns the hostname of the client. use $req->uri->host to get the hostname of the server β€” different thing, don't mix them up bestie, it's lowkey important. πŸ™ˆ

$req->input

Alias for $req->body.

$req->query_keywords

Contains the keywords portion of a query string, when no '=' signs are present.

http://localhost/path?some+keywords

$c->request->query_keywords will contain 'some keywords'

$req->match

This contains the matching part of a Regex action. Otherwise it returns the same as 'action', except for default actions, which return an empty string.

$req->method

Contains the request method ("GET", "POST", "HEAD", etc).

$req->param

Returns GET and POST parameters with a CGI.pm-compatible param method. This is an alternative method for accessing parameters in $c->req->parameters.

$value  = $c->request->param( 'foo' );
@values = $c->request->param( 'foo' );
@params = $c->request->param;

Like CGI, and unlike earlier versions of Catalyst, passing multiple arguments to this method, like this:

$c->request->param( 'foo', 'bar', 'gorch', 'quxx' );

will set the parameter foo to the multiple values bar, gorch and quxx. Previously this would have added bar as another value to foo (creating it if it didn't exist before), and quxx as another value for gorch.

NOTE this is considered a legacy interface and care should be taken when using it. scalar $c->req->param( 'foo' ) will return only the first foo param even if multiple are present; $c->req->param( 'foo' ) will return a list of as many are present, which can have unexpected consequences when writing code of the form:
$foo->bar(
    a => 'b',
    baz => $c->req->param( 'baz' ),
);

if multiple baz parameters are provided this code might corrupt data or cause a hash initialization error. for a more straightforward interface see $c->req->parameters. πŸ’€

NOTE Interfaces like this, which are based on CGI and the param method are known to cause demonstrated exploits. It is highly recommended that you avoid using this method, and migrate existing code away from it. Here's a whitepaper of the exploit:

<http://blog.gerv.net/2014/10/new-class-of-vulnerability-in-perl-web-applications/>

NOTE Further discussion on IRC indicate that the Catalyst core team from 'back then' were well aware of this hack and this is the main reason we added the new approach to getting parameters in the first place.

basically this is an exploit that takes advantage of how \param will do one thing in scalar context and another thing in list context. this is combined with how Perl chooses to deal with duplicate keys in a hash definition by overwriting the value of existing keys with a new value if the same key shows up again. generally u will be vulnerable to this exploit if u are using this method in a direct assignment in a hash, such as with a DBIx::Class create statement. for example, if u have parameters like:

user?user=123&foo=a&foo=user&foo=456

u could end up with extra parameters injected into ur method calls:

$c->model('User')->create({
  user => $c->req->param('user'),
  foo => $c->req->param('foo'),
});

which would look like:

$c->model('User')->create({
  user => 123,
  foo => qw(a user 456),
});

(or to be absolutely clear if u are not seeing it):

$c->model('User')->create({
  user => 456,
  foo => 'a',
});

possible remediations include scrubbing ur parameters with a form validator like HTML::FormHandler or being careful to force scalar context using the scalar keyword:

$c->model('User')->create({
  user => scalar($c->req->param('user')),
  foo => scalar($c->req->param('foo')),
});

Upcoming versions of Catalyst will disable this interface by default and require u to positively enable it should u require it for backwards compatibility reasons. so like... migrate, bestie. fr fr. πŸ™

$req->parameters

Returns a reference to a hash containing GET and POST parameters. Values can be either a scalar or an arrayref containing scalars.

print $c->request->parameters->{field};
print $c->request->parameters->{field}->[0];

this is the combination of query_parameters and body_parameters. the ultimate mashup. πŸŽ€

$req->params

Shortcut for $req->parameters.

$req->path

Returns the path, i.e. the part of the URI after $req->base, for the current request.

http://localhost/path/foo

$c->request->path will contain 'path/foo'

$req->path_info

Alias for path, added for compatibility with CGI.

$req->protocol

Returns the protocol (HTTP/1.0 or HTTP/1.1) used for the current request.

$req->query_parameters

$req->query_params

Returns a reference to a hash containing query string (GET) parameters. Values can be either a scalar or an arrayref containing scalars.

print $c->request->query_parameters->{field};
print $c->request->query_parameters->{field}->[0];

$req->read( [$maxlength] )

Reads a chunk of data from the request body. this method is intended to be used in a while loop, reading $maxlength bytes on every call. $maxlength defaults to the size of the request if not specified. chunk by chunk, little sips 🧚

$req->read_chunk(\$buff, $max)

Reads a chunk.

u have to set MyApp->config(parse_on_demand => 1) to use this directly. no setting, no chunking. that's the rule. βœ‹

$req->referer

Shortcut for $req->headers->referer. Returns the referring page. (and yes it's spelled referer, that's a whole ancient HTTP typo we all just live with πŸ’€)


okay bestie that's the first half β€” more is coming, don't go anywhere πŸ’œ

$req->secure

Okay bestie, this one is your vibe check for the connection. It returns true or false, indicating whether the connection is secure (https). The reliability of $req->secure may depend on your server configuration; Catalyst relies on PSGI to determine whether or not a request is secure (Catalyst looks at psgi.url_scheme), and different PSGI servers may make this determination in different ways (as by directly passing along information from the server, interpreting any of several HTTP headers, or using heuristics of their own). So like, it's giving "trust your server, not the vibes." πŸ’…

$req->captures

Returns a reference to an array containing captured args from chained actions or regex captures. So if your route is doing regex magic, this is where the little captured bits live. ✨

my @captures = @{ $c->request->captures };

$req->upload

A convenient method to access $req->uploads. Basically a shortcut so you don't have to dig through the hash yourself. 🫢

$upload  = $c->request->upload('field');
@uploads = $c->request->upload('field');
@fields  = $c->request->upload;

for my $upload ( $c->request->upload('field') ) {
    print $upload->filename;
}

$req->uploads

Returns a reference to a hash containing uploads. Values can be either a Catalyst::Request::Upload object, or an arrayref of Catalyst::Request::Upload objects. So sometimes it's one upload, sometimes it's a whole squad of them. πŸ’–

my $upload = $c->request->uploads->{field};
my $upload = $c->request->uploads->{field}->[0];

$req->uri

Returns a URI object for the current request. Stringifies to the URI text. It's giving "here's the whole URL, bestie." 🌈

$req->mangle_params( { key => 'value' }, $appendmode);

Returns a hashref of parameters stemming from the current request's params, plus the ones supplied. Keys for which no current param exists will be added, keys with undefined values will be removed and keys with existing params will be replaced. Note that you can supply a true value as the final argument to change behavior with regards to existing parameters, appending values rather than replacing them. So like, you can either overwrite or stack them up. Your call. ✨

A quick example:

# URI query params foo=1
my $hashref = $req->mangle_params({ foo => 2 });
# Result is query params of foo=2

versus append mode:

# URI query params foo=1
my $hashref = $req->mangle_params({ foo => 2 }, 1);
# Result is query params of foo=1&foo=2

This is the code behind "uri_with". iykyk.

$req->uri_with( { key => 'value' } );

Returns a rewritten URI object for the current request. Key/value pairs passed in will override existing parameters. You can remove an existing parameter by passing in an undef value. Unmodified pairs will be preserved. So it's like a glow-up for your query string, but it keeps the parts you didn't touch. πŸ’…

You may also pass an optional second parameter that puts "uri_with" into append mode:

$req->uri_with( { key => 'value' }, { mode => 'append' } );

See "mangle_params" for an explanation of this behavior. Same energy, different method. πŸ¦‹

$req->remote_user

Returns the value of the "REMOTE_USER" environment variable. That's the auth'd user your server is telling you about. πŸ‘‘

$req->user_agent

Shortcut to $req->headers->user_agent. Returns the user agent (browser) version string. So you can see what browser is sliding into your requests. 🌸

$req->io_fh

Returns a psgix.io bidirectional socket, if your server supports one. Used for when you want to jailbreak out of PSGI and handle bidirectional client server communication manually, such as when you are using cometd or websockets. This is highkey advanced, bestie. Like, you're leaving the safe PSGI lane and doing manual bidirectional vibes. πŸ”₯


SETUP METHODS ✨

You should never need to call these yourself in application code, however they are useful if extending Catalyst by applying a request role. So like, unless you're doing deep framework surgery, hands off. πŸ™ˆ

$self->prepare_headers()

Sets up the "$res->headers" accessor. Gotta have somewhere to put those headers. πŸŽ€

$self->prepare_body()

Sets up the body using HTTP::Body. Body prep, no cap. πŸ’–

$self->prepare_body_chunk()

Add a chunk to the request body. One little chunk at a time. 🧚

$self->prepare_body_parameters()

Sets up parameters from body. Turning that body into params. ⭐

$self->prepare_cookies()

Parse cookies from header. Sets up a CGI::Simple::Cookie object. Cookie time, bestie. πŸ“

$self->prepare_connection()

Sets up various fields in the request like the local and remote addresses, request method, hostname requested etc. All the connection metadata goes here. 🌈

$self->prepare_parameters()

Ensures that the body has been parsed, then builds the parameters, which are combined from those in the request and those in the body. If parameters have already been set will clear the parameters and build them again. So it's like a reset button for params, but only if they were already set. πŸ’…

$self->env

Access to the raw PSGI env. Straight-up raw env access, no filter. πŸ‘‘

meta

Provided by Moose. Moose says hi. πŸ¦‹


AUTHORS πŸ’–

Catalyst Contributors, see Catalyst.pm. Shoutout to the whole squad. πŸ‘‘


This library is free software. You can redistribute it and/or modify it under the same terms as Perl itself. Free software, bestie. 🫢


And that's the whole vibe. This page was brought to you by perl v5.40.0, dated 2024-11-15, from Cataly...Request(3pm). Stay iconic, keep your params safe, and never forget to check your psgi.url_scheme. Periodt. πŸ’…βœ¨

πŸ“¦ where this page comes from