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

DESCRIPTION

This is what your 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; ... } );

    # 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

    $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( [ $trim = 0|1 ])

Return path_info, the part of URL between script_name and parameters. Empty if no such part exists.

If trim=1 is given, removed the leading slashes.

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.

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 '') otherwise.

The regular expression is applied to the WHOLE string, from beginning to end, not just the middle. Use '.*' if you really need none.

A default value of undef is possible, but must be supplied explicitly.

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.

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.

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.

  • expires - unix timestamp when the cookie expires (overridden by ttl).

  • 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([ $noinit ])

Get reference to session data.

If set_session_handler() was called during application setup, this data will be initialized by that handler; otherwise initializes with an empty hash.

If noinit is set to true value, don't try to initialize a new session.

The reference is guaranteed to be the same throughtout the request lifetime.

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.

postpone( CODEREF->(req) )

Execute a function 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.

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_upload()

  • do_get_header_in() - returns a HTTP::Headers object.

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

  • do_write

  • do_close