NAME
MVC::Neaf::Request - Request class for Not Even A Framework
DESCRIPTION
This is what your MVC::Neaf application is going to get as its ONLY input.
Here's a brief overview of what a Neaf request returns:
# How the application was configured:
MVC::Neaf->route( "/matching/route" => sub { my $req = shift; ... },
path_info_regex => '.*' );
# What was requested:
http(s)://server.name:1337/mathing/route/some/more/slashes?foo=1&bar=2
# What is being returned:
$req->http_version = HTTP/1.0 or HTTP/1.1
$req->scheme = http or https
$req->method = GET
$req->hostname = server.name
$req->port = 1337
$req->path = /mathing/route/some/more/slashes
$req->script_name = /mathing/route
$req->path_info = some/more/slashes
# params and cookies require a regexp
$req->param( foo => '\d+' ) = 1
REQUEST METHODS
The concrete Request object the App gets is going to be a subclass of this. Thus it is expected to have the following methods.
new( %args )
The application is not supposed to make its own requests, so this constructor is really for testing purposes only.
For now, just swallows whatever given to it. Restrictions MAY BE added in the future though.
client_ip()
Returns the IP of the client. Note this may be mangled by proxy...
http_version()
Returns version number of http protocol.
scheme()
Returns http or https, depending on how the request was done.
secure()
Returns true if https:// is used, false otherwise.
method()
Return the HTTP method being used. GET is the default value if cannot find out (useful for CLI debugging).
is_post()
Alias for $self->method eq 'POST'
. May be useful in form submission, as in
$form = $request->form( $validator );
if ($request->is_post and $form->is_valid) {
# save & redirect
};
# show form again
hostname()
Returns the hostname which was requested, or "localhost" if cannot detect.
port()
Returns the port number.
path()
Returns the path part of the uri. Path is guaranteed to start with a slash.
set_path( $new_path )
Set path() to new value. This may be useful in pre_route
hook.
Path will be canonized.
If no argument given, or it is undef
, resets path() value to what was given to system value (if any).
Returns self.
script_name()
The part of the request that matched the route to the application being executed.
Guaranteed to start with slash. Unless set_path
was called, it is a prefix of path()
.
Not avilable before routing was applied to request.
get_url_base()
Get scheme, server, and port of the application.
EXPERIMENTAL Name and meaning subject to change.
get_url_rel( %override )
Produce a relative link to the page being served, possibly overriding some parameters.
Parameter order is NOT preserved. If parameter is empty or undef, it is skipped.
CAUTION Multi-values are ignored, this MAY change in the future.
CAUTION For a POST request, normal parameters are used instead of URL parameters (see url_param
). This MAY change in the future.
EXPERIMENTAL Name and meaning subject to change.
get_url_full( %override )
Same as above, but prefixed with schema, server name, and port.
EXPERIMENTAL Name and meaning subject to change.
path_info()
Returns the part of URI path beyond what matched the application's path.
Contrary to the CGI specification, the leading slash is REMOVED.
The validation regexp for this value MUST be specified during application setup as path_info_regex
. See route
in MVC::Neaf.
NOTE Experimental. This part of API is undergoing changes.
path_info_split
Return a list of matched capture groups found in path_info_regex, if any.
EXPERIMENTAL Name and meaning subject to change.
set_path_info ( $path_info )
Sets path_info to new value.
Also updates path() value so that path = script_name + path_info still holds.
Returns self.
param($name, $regex [, $default])
Return param, if it passes regex check, default value or undef otherwise.
The regular expression is applied to the WHOLE string, from beginning to end, not just the middle. Use '.*' if you really trust the data.
EXPERIMENTAL If param_regex
hash was given during route definition, $regex
MAY be omitted for params that were listed there. This feature is not stable yet, though. Use with care.
If method other than GET/HEAD is being used, whatever is in the address line after ? is IGNORED. Use url_param() (see below) if you intend to mix GET/POST parameters.
NOTE param() ALWAYS returns a single value, even in list context. Use multi_param() (see below) if you really want a list.
NOTE param() has nothing to do with getting parameter list from request. Instead, use form with wildcards:
neaf form => "my_form" => [ [ 'guest\d+' => '.*'], [ 'arrival\d+' => '.*' ] ],
engine => 'Wildcard';
# later in controller
my $guests = $req->form("my_form");
$guests->fields; # has guest1 & arrival1, guest2 & arrival2 etc
$guests->error; # hash with values that didn't match regexp
See MVC::Neaf::X::Form::Wildcard.
url_param( name => qr/regex/ )
If method is GET or HEAD, identic to param.
Otherwise would return the parameter from query string, AS IF it was a GET request.
Multiple values are deliberately ignored.
See CGI.
multi_param( name => qr/regex/ )
Get a single multivalue GET/POST parameter as a @list. The name generally follows that of newer CGI (4.08+).
ALL values must match the regex, or an empty list is returned.
EXPERIMENTAL If param_regex
hash was given during route definition, $regex
MAY be omitted for params that were listed there. This feature is not stable yet, though. Use with care.
EXPERIMENTAL This method's behaviour MAY change in the future. Please be careful when upgrading.
set_param( name => $value )
Override form parameter. Returns self.
form( $validator )
Apply validator to raw params and return whatever it returns.
A validator MUST be an object with validate
method, or a coderef, or a symbolic name registered earlier via neaf form ...
.
Neaf's own validators, MVC::Neaf::X::Form
and MVC::Neaf::X::Form::LIVR
, will return a MVC::Neaf::X::Form::Data
object with the following methods:
is_valid - tells whether data passed validation
error - hash of errors, can also be modified if needed:
$result->error( myfield => "Correct, but not found in database" );
data - hash of valid, cleaned data
raw - hash of data entered initially, may be useful to display input form again.
You are encouraged to use this return format from your own validation class or propose improvements.
get_form_as_list ( qr/.../, qw(name1 name2 ...) )
get_form_as_list ( [ qr/.../, "default" ], qw(name1 name2 ...) )
Return a group of uniform parameters as a list, in that order. Values that fail validation are returned as undef, unless default given.
EXPERIMENTAL. The name MAY be changed in the future.
body()
Returns request body for PUT/POST requests. This is not regex-checked - the check is left for the user.
Also the data is NOT converted to utf8.
upload_utf8( "name" )
Returns an MVC::Neaf::Upload object corresponding to an uploaded file, if such uploaded file is present.
All data read from such upload will be converted to unicode, raising an exception if decoding ever fails.
An upload object has at least handle
and content
methods to work with data:
my $upload = $req->upload("user_file");
if ($upload) {
my $untrusted_filename = $upload->filename;
my $fd = $upload->handle;
while (<$fd>) {
...
};
}
or just
if ($upload) {
while ($upload->content =~ /(...)/g) {
do_something($1);
};
};
upload_raw( "name" )
Like above, but no decoding whatsoever is performed.
upload( "name" )
DEPRECATED. Same as upload_raw, but issues a warning.
get_cookie ( "name" => qr/regex/ [, "default" ] )
Fetch client cookie. The cookie MUST be sanitized by regular expression.
The regular expression is applied to the WHOLE string, from beginning to end, not just the middle. Use '.*' if you really need none.
set_cookie( name => "value", %options )
Set HTTP cookie. %options may include:
regex - regular expression to check outgoing value
ttl - time to live in seconds. 0 means no ttl. Use negative ttl and empty value to delete cookie.
expire - unix timestamp when the cookie expires (overridden by ttl).
expires - DEPRECATED - use 'expire' instead (w/o 's')
domain
path
httponly - flag
secure - flag
Returns self.
delete_cookie( "name" )
Remove cookie by setting value to an empty string, and expiration in the past. NOTE It is up to the user agent to actually remove cookie.
Returns self.
format_cookies
Converts stored cookies into an arrayref of scalars ready to be put into Set-Cookie header.
error ( status )
Report error to the CORE.
This throws an MVC::Neaf::Exception object.
If you're planning calling $req->error within eval block, consider using neaf_err function to let it propagate:
use MVC::Neaf::Exception qw(neaf_err);
eval {
$req->error(422)
if ($foo);
$req->redirect( "http://google.com" )
if ($bar);
};
if ($@) {
neaf_err($@);
# The rest of the catch block
};
redirect( $location )
Redirect to a new location.
This throws an MVC::Neaf::Exception object. See error()
discussion above.
header_in()
header_in( "header_name" )
Fetch HTTP header sent by client. Header names are lowercased, dashes converted to underscores. So "Http-Header", "HTTP_HEADER" and "http_header" are all the same.
Without argument, returns a HTTP::Headers::Fast object.
With a name, returns all values for that header in list context, or ", " - joined value as one scalar in scalar context - this is actually a frontend to HTTP::Headers::Fast header() method.
EXPERIMENTAL The return value format MAY change in the near future.
header_in_keys ()
Return all keys in header_in object as a list.
EXPERIMENTAL. This may change or disappear altogether.
referer
Get/set referer.
NOTE Avoid using referer for anything serious - too easy to forge.
user_agent
Get/set user_agent.
NOTE Avoid using user_agent for anything serious - too easy to forge.
dump ()
Dump whatever came in the request. Useful for debugging.
SESSION MANAGEMENT
session()
Get reference to session data. This reference is guaranteed to be the same throughtout the request lifetime.
If MVC::Neaf->set_session_handler() was called during application setup, this data will be initialized by that handler; otherwise initializes with an empty hash (or whatever session engine generates).
If session engine was not provided, dies instead.
See MVC::Neaf::X::Session for details about session engine internal API.
load_session
Like above, but don't create session - just fetch from cookies & storage.
Never tries to load anything if session already loaded or created.
save_session( [$replace] )
Save whatever is in session data reference.
If argument is given, replace session (if any) altogether with that one before saving.
delete_session()
Remove session.
REPLY METHODS
Typically, a Neaf user only needs to return a hashref with the whole reply to client.
However, sometimes more fine-grained control is required.
In this case, a number of methods help stashing your data (headers, cookies etc) in the request object until the responce is sent.
Also some lengthly actions (e.g. writing request statistics or sending confirmation e-mail) may be postponed until the request is served.
header_out( [$param] )
Without parameters returns a HTTP::Headers::Fast-compatible object containing all headers to be returned to client.
With one parameter returns this header.
Returned values are just proxied HTTP::Headers::Fast returns. It is generally advised to use them in list context as multiple headers may return trash in scalar context.
E.g.
my @old_value = $req->header_out( foobar => set => [ "XX", "XY" ] );
or
my $old_value = [ $req->header_out( foobar => delete => 1 ) ];
NOTE This format may change in the future.
set_header( $name, $value || [] )
push_header( $name, $value || [] )
remove_header( $name )
Set, append, and delete values in the header_out object. See HTTP::Headers::Fast.
Arrayrefs are ok and will set multiple values for a given header.
reply
Returns reply hashref that was returned by controller, if any. Returns undef unless the controller was actually called. This may be useful in postponed actions or hooks.
This is killed by a clear()
call.
stash()
stash( "name" )
stash( %save_data )
A hashref that is guaranteed to persist throughout the request lifetime.
This may be useful to maintain shared data accross hooks and callbacks.
Use session
if you intend to share data between requests.
Use reply
if you intend to render the data for the user.
Use stash
as a last resort for temporary, private data.
Stash is not killed by clear()
function so that cleanup isn't botched accidentally.
postpone( CODEREF->(req) )
postpone( [ CODEREF->(req), ... ] )
Execute a function (or several) right after the request is served.
Can be called multiple times.
CAVEAT: If CODEREF contains reference to the request, the request will never be destroyed due to circular reference. Thus CODEREF may not be executed.
Don't pass request to CODEREF, use my $req = shift
instead if really needed.
Returns self.
write( $data )
Write data to client inside -continue
callback, unless close
was called.
Returns self.
close()
Stop writing to client in -continue
callback.
By default, does nothing, as the socket will probably be closed anyway when the request finishes.
clear()
Remove all data that belongs to reply. This is called when a handler bails out to avoid e.g. setting cookies in a failed request.
DEVELOPER METHODS
id()
Lazily fetch unique request id. These are guaranteed to be unique on a given machine within a reasonable timeframe.
Current id-generation mechanism involves url-safe md5_base64 [-_]
, but this MAY change in the future.
CAUTION Don't use this id for anything secure. Use MVC::Neaf::X::Session's ids instead. This one is just for information.
set_id( $new_value )
Set the id above to a user-supplied value.
If a false value given, just generate a new one next time id is requested.
Symbols outside ascii, as well as shitespace and "
and C"\", are prohibited.
Returns the request object.
log_error( $message )
Log an error message, annotated with request id and the route being processed.
Currently works via warn, but this may change in the future.
EXPERIMENTAL. This feature is still under development.
One can count on log_error
to be available in the future and do some king of logging.
endpoint_origin
Returns file:line where controller was defined.
DEPRECATED. Do not use.
execute_postponed()
NOT TO BE CALLED BY USER.
Execute postponed functions. This is called in DESTROY by default, but request driver may decide it knows better.
Flushes postponed queue. Ignores exceptions in functions being executed.
Returns self.
DRIVER METHODS
The following methods MUST be implemented in every Request subclass to create a working Neaf backend.
They shall not generally be called directly inside the app.
do_get_client_ip()
do_get_http_version()
do_get_method()
do_get_scheme()
do_get_hostname()
do_get_port()
do_get_path()
do_get_params()
do_get_param_as_array() - get single GET/POST param in list context
do_get_upload()
do_get_body()
do_get_header_in() - returns a HTTP::Headers::Fast object.
do_reply( $status, $content ) - write reply to client
do_reply( $status ) - only send headers to client
do_write( $data )
do_close()
do_log_error()
DEPRECATED METHODS
Some methods become obsolete during Neaf development. Anything that is considered deprecated will continue to be supported for at least three minor versions after official deprecation and a corresponding warning being added.
Please keep an eye on Changes
though.
Here are these methods, for the sake of completeness.
set_full_path( $path )
set_full_path( $script_name, $path_info )
Set new path elements which will be returned from this point onward.
Also updates path() value so that path = script_name + path_info still holds.
set_full_path(undef) resets script_name to whatever returned by the underlying driver.
Returns self.
DEPRECATED Use set_path() and set_path_info() instead.
get_form_as_hash ( name => qr/.../, name2 => qr/..../, ... )
DEPRECATED and dies. Use MVC::Neaf::X::Form instead.
set_default( key => $value, ... )
As of v.0.20 this dies.
USe path-based defaults, or stash().
get_default()
As of v.0.20 this dies.
USe path-based defaults, or stash().
LICENSE AND COPYRIGHT
Copyright 2016-2017 Konstantin S. Uvarin khedin@cpan.org
.
This program is free software; you can redistribute it and/or modify it under the terms of either: the GNU General Public License as published by the Free Software Foundation; or the Artistic License.
See http://dev.perl.org/licenses/ for more information.