The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.

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.

script_name()

The part of the request that mathed the route to the application being executed. Guaranteed to start with slash and be a prefix of path().

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 SHOULD be specified during application setup as path_info_regex. See route in MVC::Neaf.

NOTE Starting v.0.16 of this module, path_info() will die unless validation regexp was provided.

NOTE Experimental. This part of API is undergoing changes.

set_full_path( $path )

set_full_path( $script_name, $path_info, $no_path_info_regex=1|0 )

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.

NOTE This is an internal method, don't call it unless you know what you're doing.

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 need none.

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 Behaviour changed since 0.11 - missing default value no more interpreted as '', returns undef.

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 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.

Validator MUST either be a CODEREF, or be an object with validate() method accepting a hashref.

See MVC::Neaf::X::Form for details on Neaf's built in validator.

get_form_as_hash ( name => qr/.../, name2 => qr/..../, ... )

Return a group of form parameters as a hashref. Only values that pass corresponding validation are added.

DEPRECATED. Use MVC::Neaf::X::Form instead.

get_form_as_list ( qr/.../, qw(name1 name2 ...) )

get_form_as_list ( [ qr/.../, "default" ], qw(name1 name2 ...) )

Return a group of form parameters as a list, in that order. Values that fail validation are returned as undef, unless default given.

DEPRECATED. Use MVC::Neaf::X::Form instead.

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.

set_default( key => $value, ... )

Set default values for your return hash. May be useful inside MVC::Neaf->pre_route.

Returns self.

EXPERIMANTAL. API and naming subject to change.

get_default()

Returns a hash of previously set default values.

EXPERIMANTAL. API and naming subject to change.

upload( "name" )

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() dsicussion 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 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 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 object containing all headers to be returned to client.

With one parameter returns this header.

Returned values are just proxied HTTP::Headers 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.

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.

EXPERIMENTAL. This function MAY be removed or changed in the future.

stash()

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.

EXPERIMENTAL. This function MAY be removed if hooks turn out to be too cumbersome.

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.

METHODS FOR DRIVER DEVELOPERS

The following methods are to be used/redefined by backend writers (e.g. if someone makes Request subclass for FastCGI or Microsoft IIS).

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 object.

  • do_reply( $status, $content ) - write reply to client

  • do_write

  • do_close