NAME

Net::API::REST::Request - Apache2 Incoming Request Access and Manipulation

SYNOPSIS

use Net::API::REST::Request;
## $r is the Apache2::RequestRec object
my $req = Net::API::REST::Request->new( request => $r, debug => 1 );
## or, to test it outside of a modperl environment:
my $req = Net::API::REST::Request->new( request => $r, debug => 1, checkonly => 1 );

VERSION

v0.8.3

DESCRIPTION

The purpose of this module is to provide an easy access to various method to process and manipulate incoming request.

This is designed to work under modperl.

Normally, one would need to know which method to access across various Apache2 mod perl modules, which makes development more time consuming and even difficult, because of the scattered documentation and even sometime outdated.

This module alleviate this problem by providing all the necessary methods in one place. Also, at the contrary of Apache2 modules suit, all the methods here are die safe. When an error occurs, it will always return undef() and the error will be able to be accessed using error object, which is a Module::Generic::Exception object.

Fo its alter ego to manipulate outgoing http response, use the Net::API::REST::Response module.

METHODS

new( hash )

This initiates the package and take the following parameters:

request

This is a required parameter to be sent with a value set to a Apache2::RequestRec object

checkonly

If true, it will not perform the initialisation it would usually do under modperl.

debug

Optional. If set with a positive integer, this will activate verbose debugging message

aborted()

Tells whether the connection has been aborted or not

accept()

Returns the http Accept header value, such as text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8

accept_encoding()

Returns the http Accept-Encoding header value

accept_language()

Returns the http Accept-Language header value such as en-GB,fr-FR;q=0.8,fr;q=0.6,ja;q=0.4,en;q=0.2

allowed()

Returns the allowed methods, such as GET, POST, PUT, OPTIONS, HEAD, etc

as_string()

Returns the http request as a string

auth()

Returns the Authorization header value if any. This ill have been processed upo object initiation phase.

authorization()

Returns the http authorization header value. This is similar to auth().

auth_type()

Returns the authentication type

auto_header( boolean )

Given a boolean value, this enables the auto header or not. In the back, this calls the method assbackwards

If this is disabled, you need to make sure to manually update the counter, such as:

$req->connection->keepalives( $req->connection->keepalives + 1 );

See Apache2::RequestRec for more information on this.

body( name )

Returns an APR::Request::Param::Table object containing the POST data parameters of the Apache2::Request object.

my $body = $req->body;

An optional name parameter can be passed to return the POST data parameter associated with the given name:

my $foo_body = $req->body("foo");

This is similar to the param method with slight difference. Check Apache2::Request for more information.

charset()

Returns the charset, if any, found in the http request received and processed upon initialisation of this module object.

checkonly( boolean )

This is also an object initialisation property.

If true, this will discard the normal processing of incoming http request under modperl.

This is useful and intended when testing this module offline.

child_terminate()

Terminate the current worker process as soon as the current request is over.

See Apache::RequestUtil for more information.

client_api_version()

Returns the client api version requested, if provided. This is set during the object initialisation phase.

An example header to require api version 1.0 would be:

Accept: application/json; version=1.0; encoding=utf-8

close()

This close the client connection.

This is not implemented in by APR::Socket, so this is an efficient work around.

However, a word of caution, you most likely do not need or want to close manually the client connection and instea have your method return Apache2::Const::OK or any other constant matching the http code you want to return.

code()

Returns the response status code.

From the Apache2::RequestRec documentation:

Usually you will set this value indirectly by returning the status code as the handler's function result. However, there are rare instances when you want to trick Apache into thinking that the module returned an "Apache2::Const::OK" status code, but actually send the browser a non-OK status. This may come handy when implementing an HTTP proxy handler. The proxy handler needs to send to the client, whatever status code the proxied server has returned, while returning "Apache2::Const::OK" to Apache. e.g.:

$req->status( $some_code );
return( Apache2::Const::OK );

connection()

Returns a Apache2::Connection object.

connection_id()

Returns the connection id; unique at any point in time. See Apache2::Connection for more information.

content()

Returns the content of the file specified with $req-filename>. It calls slurp_filename from Apache2::Request, but instead of returning a scalar reference, it returns the data itself.

content_encoding()

Returns the value of the Content-Encoding HTTP response header

content_languages()

Retrieves the value of the Content-Language HTTP header

content_length()

Returns the length in byte of the request body.

content_type()

Retrieves the value of the Content-type header value. See Apache2::RequestRec for more information.

cookie( name )

Returns the current value for the given cookie name.

This works by calling the cookies method, which returns a cookie jar object which is a Net::API::REST::Cookies object.

cookies()

Returns a Net::API::REST::Cookies object acting as a jar with various methods to access, manipulate and create cookies.

data()

Read the incoming data payload and decode it from its encoded charset into perl internal utf8.

This is specifically designed for json payload.

It returns a string of data.

document_root( [ string ] )

Retrieve the document root for this server.

If a value is provided, it sets the document root to a new value only for the duration of the current request.

See Apache2::RequestUtil for more information.

env

err_headers_out( hash )

Get/set MIME response headers, printed even on errors and persist across internal redirects.

According to the Apache2::RequestRec documentation:

The difference between "headers_out" and "err_headers_out", is that the latter are printed even on error, and persist across internal redirects (so the headers printed for "ErrorDocument" handlers will have them).

For example, if a handler wants to return a 404 response, but nevertheless to set a cookie, it has to be:

$r->err_headers_out->add( 'Set-Cookie' => $cookie );
return( Apache2::Const::NOT_FOUND );

If the handler does:

$r->headers_out->add( 'Set-Cookie' => $cookie );
return( Apache2::Const::NOT_FOUND );

the Set-Cookie header won't be sent.

See Apache2::RequestRec for more information.

filename( string )

Get/set the filename on disk corresponding to this response

See Apache2::RequestRec for more information.

finfo()

Get and set the finfo request record member

See Apache2::RequestRec for more information.

get_handlers( hook_name )

Returns a reference to a list of handlers enabled for a given phase.

$handlers_list = $r->get_handlers( $hook_name );

Example, a list of handlers configured to run at the response phase:

my @handlers = @{ $r->get_handlers('PerlResponseHandler') || [] };

get_status_line()

Return the "Status-Line" for a given status code (excluding the HTTP-Version field).

For example:

print( $req->get_status_line( 400 ) );

will print:

400 Bad Request

global_request()

Returns the Apache2::RequestRec object made global with the proper directive in the Apache VirtualHost configuration.

This calls the module Apache::RequestUtil to retrieve this value.

headers( string )

Returns a hash reference of headers key => value pairs. If a header name is provided, this will return its value instead.

This calls the method headers_in() behind.

headers_as_hashref()

Returns the list of headers as an hash reference.

headers_as_json()

Returns the list of headers as a json data

headers_in()

Returns the list of the headers as hash or the individual value of a header:

my $cookie = $r->headers_in->{Cookie} || '';

headers_out( name, [ value ] )

Returns or sets the key => value pairs of outgoing http headers, only on 2xx responses.

See also "err_headers_out", which allows to set headers for non-2xx responses and persist across internal redirects.

More information at Apache2::RequestRec

hostname( [ hostname ] )

Retrieve or set the http server host name, such as www.example.com.

This is not the machine hostname.

More information at Apache2::RequestRec

http_host()

Returns an URI object of the http host being accessed. This is created during object initiation phase.

id()

Returns the connection id; unique at any point in time. See Apache2::Connection for more information.

This is the same as connection_id()

if_modified_since()

Returns the value of the http header If-Modified-Since as a DateTime object.

If no such header exists, it returns undef()

if_none_match()

Returns the value of the http header If-None-Match

input_filters( [ filter ] )

Get/set the first filter in a linked list of request level input filters. It returns a Apache2::Filter object.

$input_filters      = $r->input_filters();
$prev_input_filters = $r->input_filters( $new_input_filters );

According to the Apache2::RequestRec documentation:

For example instead of using $r-read()> to read the POST data, one could use an explicit walk through incoming bucket brigades to get that data. The following function read_post() does just that (in fact that's what $r-read()> does behind the scenes):

 use APR::Brigade ();
 use APR::Bucket ();
 use Apache2::Filter ();

 use Apache2::Const -compile => qw(MODE_READBYTES);
 use APR::Const    -compile => qw(SUCCESS BLOCK_READ);

 use constant IOBUFSIZE => 8192;

 sub read_post {
	 my $r = shift;

	 my $bb = APR::Brigade->new($r->pool,
								$r->connection->bucket_alloc);

	 my $data = '';
	 my $seen_eos = 0;
	 do {
		 $r->input_filters->get_brigade($bb, Apache2::Const::MODE_READBYTES,
										APR::Const::BLOCK_READ, IOBUFSIZE);

		 for (my $b = $bb->first; $b; $b = $bb->next($b)) {
			 if ($b->is_eos) {
				 $seen_eos++;
				 last;
			 }

			 if ($b->read(my $buf)) {
				 $data .= $buf;
			 }

			 $b->remove; # optimization to reuse memory
		 }

	 } while (!$seen_eos);

	 $bb->destroy;

	 return $data;
 }

As you can see $r-input_filters> gives us a pointer to the last of the top of the incoming filters stack.

is_header_only()

Returns a boolean value on whether the request is a HEAD request or not.

is_perl_option_enabled()

Check whether a directory level "PerlOptions" flag is enabled or not. This returns a boolean value.

For example to check whether the "SetupEnv" option is enabled for the current request (which can be disabled with "PerlOptions -SetupEnv") and populate the environment variables table if disabled:

$r->subprocess_env unless $r->is_perl_option_enabled('SetupEnv');

See also: PerlOptions and the equivalent function for server level PerlOptions flags.

See the Apache2::RequestUtil module documentation for more information.

json()

Returns a JSON object with the relaxed attribute enabled so that it allows more relaxed json data.

keepalive()

This method answers the question: Should the the connection be kept alive for another HTTP request after the current request is completed?

 use Apache2::Const -compile => qw(:conn_keepalive);
 ...
 my $c = $r->connection;
 if ($c->keepalive == Apache2::Const::CONN_KEEPALIVE) {
	 # do something
 }
 elsif ($c->keepalive == Apache2::Const::CONN_CLOSE) {
	 # do something else
 }
 elsif ($c->keepalive == Apache2::Const::CONN_UNKNOWN) {
	 # do yet something else
 }
 else {
	 # die "unknown state";
 }

Notice that new states could be added later by Apache, so your code should make no assumptions and do things only if the desired state matches.

See Apache2::Connection for more information.

keepalives()

How many requests were already served over the current connection.

This method is only relevant for keepalive connections. The core connection output filter "ap_http_header_filter" increments this value when the response headers are sent and it decides that the connection should not be closed (see "ap_set_keepalive()").

If you send your own set of HTTP headers with "$r->assbackwards", which includes the "Keep-Alive" HTTP response header, you must make sure to increment the "keepalives" counter.

See Apache2::Connection for more information.

languages()

This will check the Accept-Languages http headers and derived a list of priority ordered user preferred languages and return an array reference.

See also the preferred_language method.

length()

Returns the length in bytes of the request body.

local_host()

Used for ap_get_server_name when UseCanonicalName is set to DNS (ignores setting of HostnameLookups)

Better to use the server_name instead.

local_ip()

Return our server IP address as string.

location()

Get the path of the <Location> section from which the current "Perl*Handler" is being called.

Returns a string.

log_error( string )

main()

Get the main request record and returns a Apache2::RequestRec object.

If the current request is a sub-request, this method returns a blessed reference to the main request structure. If the current request is the main request, then this method returns undef.

To figure out whether you are inside a main request or a sub-request/internal redirect, use $r-is_initial_req>.

method( string )

Get/set the current request method (e.g. "GET", "HEAD", "POST", etc.).

if a new value was passed the previous value is returned.

mtime()

Last modified time of the requested resource.

Returns a timestamp in second since epoch.

next()

Pointer to the redirected request if this is an external redirect.

Returns a Apache2::RequestRec blessed reference to the next (internal) request structure or undef if there is no next request.

no_cache()

Add/remove cache control headers. A true value sets the "no_cache" request record member to a true value and inserts:

Pragma: no-cache
Cache-control: no-cache

into the response headers, indicating that the data being returned is volatile and the client should not cache it.

A false value unsets the "no_cache" request record member and the mentioned headers if they were previously set.

This method should be invoked before any response data has been sent out.

See Apache2::RequestUtil for more information.

notes( string )

Get/set text notes for the duration of this request. These notes can be passed from one module to another (not only mod_perl, but modules in any other language).

If a new value was passed, returns the previous value.

The returned value is a APR::Table object.

output_filters( [ filter ] )

Get the first filter in a linked list of request level output filters. It returns a Apache2::Filter object.

If a new output filters was passed, returns the previous value.

According to the Apache::RequestRec documentation:

For example instead of using $r-print()> to send the response body, one could send the data directly to the first output filter. The following function send_response_body() does just that:

 use APR::Brigade ();
 use APR::Bucket ();
 use Apache2::Filter ();

 sub send_response_body 
 {
	 my( $r, $data ) = @_;

	 my $bb = APR::Brigade->new( $r->pool,
								 $r->connection->bucket_alloc );

	 my $b = APR::Bucket->new( $bb->bucket_alloc, $data );
	 $bb->insert_tail( $b );
	 $r->output_filters->fflush( $bb );
	 $bb->destroy;
 }

In fact that's what $r-read()> does behind the scenes. But it also knows to parse HTTP headers passed together with the data and it also implements buffering, which the above function does not.

params( key => value )

Get the request parameters (using case-insensitive keys) by mimicing the OO interface of CGI::param.

It can take as argument, only a key and it will then retrive the corresponding value, or it can take a key and value pair.

If the value is an array, this will set multiple entry of the key for each value provided.

This uses Apache APR::Table and works for both POST and GET methods.

If the methods received was a GET method, this method returns the value of the query method instead.

path_info( string )

Get/set the PATH_INFO, what is left in the path after the URI --> filename translation.

Return a string as the current value.

payload()

Returns the json data decoded into a perl structure. This is set at object initiation phase and calls the data method to read the incoming data and decoded it into perl internal utf8.

per_dir_config()

Get the dir config vector. Returns a Apache2::ConfVector object.

For an in-depth discussion, refer to the Apache Server Configuration Customization in Perl chapter.

pnotes()

Share Perl variables between Perl HTTP handlers.

# to share variables by value and not reference, $val should be a lexical.
$old_val  = $r->pnotes( $key => $val );
$val      = $r->pnotes( $key );
$hash_ref = $r->pnotes();

Note: sharing variables really means it. The variable is not copied. Only its reference count is incremented. If it is changed after being put in pnotes that change also affects the stored value. The following example illustrates the effect:

my $v=1;                     my $v=1;
$r->pnotes( 'v'=>$v );       $r->pnotes->{v}=$v;
$v++;                        $v++;
my $x=$r->pnotes('v');       my $x=$r->pnotes->{v};

pool()

Returns the pool associated with the request as a APR::Pool object.

preferred_language( array ref )

Given an array reference of supported languages, this method will get the client accepted languages and derived the best match, ie the client preferred language.

It returns a string representing a language code.

prev()

Pointer to the previous request if this is an internal redirect.

Returns a Apache2::RequestRec blessed reference to the previous (internal) request structure or "undef" if there is no previous request.

protocol()

Get a string identifying the protocol that the client speaks, such as HTTP/1.0 or HTTP/1.1

proxyreq()

Get/set the proxyrec request record member and optionally adjust other related fields.

Valid values are: PROXYREQ_NONE, PROXYREQ_PROXY, PROXYREQ_REVERSE, PROXYREQ_RESPONSE

According to the Apache2::RequestRec documentation:

For example to turn a normal request into a proxy request to be handled on the same server in the "PerlTransHandler" phase run:

my $real_url = $r->unparsed_uri;
$r->proxyreq(Apache2::Const::PROXYREQ_PROXY);
$r->uri($real_url);
$r->filename("proxy:$real_url");
$r->handler('proxy-server');

Also remember that if you want to turn a proxy request into a non-proxy request, it's not enough to call:

$r->proxyreq(Apache2::Const::PROXYREQ_NONE);

You need to adjust "$r->uri" and "$r->filename" as well if you run that code in "PerlPostReadRequestHandler" phase, since if you don't -- "mod_proxy"'s own post_read_request handler will override your settings (as it will run after the mod_perl handler).

And you may also want to add

$r->set_handlers(PerlResponseHandler => []);

so that any response handlers which match apache directives will not run in addition to the mod_proxy content handler.

push_handlers( name => code reference )

Add one or more handlers to a list of handlers to be called for a given phase.

$ok = $r->push_handlers($hook_name => \&handler);
$ok = $r->push_handlers($hook_name => ['Foo::Bar::handler', \&handler2]);

It returns a true value on success, otherwise a false value

Examples:

A single handler:

$r->push_handlers(PerlResponseHandler => \&handler);

Multiple handlers:

$r->push_handlers(PerlFixupHandler => ['Foo::Bar::handler', \&handler2]);

Anonymous functions:

$r->push_handlers(PerlLogHandler => sub { return Apache2::Const::OK });

See Apache::RequestUtil for more information.

query()

Check the query string sent in the http request, which obviously should be a GET, but not necessarily, and parse it with URI::Query and return a hash reference.

query_string( query string )

Actually calls args from Apache2::RequestRec behind the scene.

This get/set the request QUERY string.

read()

Read data from the client and returns the number of characters actually read.

$cnt = $r->read($buffer, $len);
$cnt = $r->read($buffer, $len, $offset);

This method shares a lot of similarities with the Perl core read() function. The main difference in the error handling, which is done via APR::Error exceptions

See Apache2::RequestIO for more information.

referer()

Returns the value of the Referer http header, if any.

remote_addr()

Returns the remote host socket address

This checks which version of Apache is running, because the Apache2 mod_perl api has changed.

remote_host()

Returns the remote client host name.

remote_ip()

Returns the ip address of the client, ie remote host making the request.

It returns a string representing an ip address,

reply( code integer, hash reference )

This method is used to return a json reply back to the client.

It takes a http constant integer value representing the http status code and a hash reference containing the message property with a string to be sent.

It will convert the perl hash into a json string and return it to the client after setting the http response code.

This method is actually discouraged in favour of the equivalent one reply in Net::API::REST, which is more powerful and versatile.

request()

Returns the embedded Apache2::RequestRec object provided initially at object initiation.

request_time()

Time when the request started in second since epoch.

server()

Get the Apache2::ServerRec object for the server the request $r is running under.

server_admin()

Returns the server admin as provided by Apache2::ServerRec

server_hostname()

Returns the server host name as provided by Apache2::ServerRec

server_name()

Get the current request's server name

See Apache2::RequestUtil for more information.

server_port()

Get the current server port

See Apache2::RequestUtil for more information.

server_version

set_basic_credentials( user_name, password )

Populate the incoming request headers table ("headers_in") with authentication headers for Basic Authorization as if the client has submitted those in first place:

$r->set_basic_credentials( $username, $password );

See Apache2::RequestUtil for more information.

set_handlers()

Set a list of handlers to be called for a given phase. Any previously set handlers are forgotten.

See Apache2::RequestUtil for more information.

$ok = $r->set_handlers($hook_name => \&handler);
$ok = $r->set_handlers($hook_name => ['Foo::Bar::handler', \&handler2]);
$ok = $r->set_handlers($hook_name => []);
$ok = $r->set_handlers($hook_name => undef);

slurp_filename()

Slurp the contents of $req-filename>:

This returns a scalar reference instead of the actual string. To get the string, use content

Note that if you assign to "$req->filename" you need to update its stat record.

socket()

Get/set the client socket and returns a APR::Socket object.

This calls the client_socket method of the Apache2::Connection package.

status( [ integer ] )

Get/set the reply status for the client request.

Normally you would use some Apache2::Const constant, e.g. Apache2::Const::REDIRECT.

From the Apache2::RequestRec documentation:

Usually you will set this value indirectly by returning the status code as the handler's function result. However, there are rare instances when you want to trick Apache into thinking that the module returned an Apache2::Const:OK status code, but actually send the browser a non-OK status. This may come handy when implementing an HTTP proxy handler. The proxy handler needs to send to the client, whatever status code the proxied server has returned, while returning Apache2::Const::OK to Apache. e.g.:

$r->status( $some_code );
return( Apache2::Const::OK );

See also $r-status_line>, which. if set, overrides $r-status>.

status_line( string )

Get/set the response status line. The status line is a string like 200 Document follows and it will take precedence over the value specified using the $r-status()> described above.

According to the Apache2::RequestRec documentation:

When discussing $r-status> we have mentioned that sometimes a handler runs to a successful completion, but may need to return a different code, which is the case with the proxy server. Assuming that the proxy handler forwards to the client whatever response the proxied server has sent, it'll usually use status_line(), like so:

$r->status_line( $response->code() . ' ' . $response->message() );
return( Apache2::Const::OK );

In this example $response could be for example an "HTTP::Response" object, if "LWP::UserAgent" was used to implement the proxy.

This method is also handy when you extend the HTTP protocol and add new response codes. For example you could invent a new error code and tell Apache to use that in the response like so:

$r->status_line( "499 We have been FooBared" );
return( Apache2::Const::OK );

Here 499 is the new response code, and We have been FooBared is the custom response message.

subprocess_env()

Get/set the Apache subprocess_env table, or optionally set the value of a named entry.

From the Apache2::RequestRec documentation:

When called in VOID context with no arguments, it populate %ENV with special variables (e.g. $ENV{QUERY_STRING}) like mod_cgi does.

When called in a non-VOID context with no arguments, it returns an "APR::Table object".

When the $key argument (string) is passed, it returns the corresponding value (if such exists, or "undef". The following two lines are equivalent:

$val = $r->subprocess_env($key);
$val = $r->subprocess_env->get($key);

When the $key and the $val arguments (strings) are passed, the value is set. The following two lines are equivalent:

$r->subprocess_env($key => $val);
$r->subprocess_env->set($key => $val);

The "subprocess_env" "table" is used by "Apache2::SubProcess", to pass environment variables to externally spawned processes. It's also used by various Apache modules, and you should use this table to pass the environment variables. For example if in "PerlHeaderParserHandler" you do:

$r->subprocess_env(MyLanguage => "de");

you can then deploy "mod_include" and write in .shtml document:

<!--#if expr="$MyLanguage = en" -->
English
<!--#elif expr="$MyLanguage = de" -->
Deutsch
<!--#else -->
Sorry
<!--#endif -->

the_request()

Get or set the first HTTP request header as a string. For example:

GET /foo/bar/my_path_info?args=3 HTTP/1.0

type()

Returns the content type of the request received. This value is set at object initiation phase.

unparsed_uri()

The URI without any parsing performed.

If for example the request was:

GET /foo/bar/my_path_info?args=3 HTTP/1.0

"$r->uri" returns:

/foo/bar/my_path_info

whereas "$r->unparsed_uri" returns:

/foo/bar/my_path_info?args=3

uri()

Returns a URI object representing the full uri of the request.

This is different from the original Apache2::RequestRec which only returns the path portion of the URI.

So, to get the path portion using our uri method, one would simply do $req-uri->path()>

user()

Get the user name, if an authentication process was successful. Or set it.

For example, let's print the username passed by the client:

my( $res, $sent_pw ) = $req->get_basic_auth_pw;
return( $res ) if( $res != Apache2::Const::OK );
print( "User: ", $r->user );

user_agent()

Returns the user agent, ie the browser signature as provided in the request headers received under the http header User-Agent

variables()

When parsing the endpoint sought by the client request, there may be some variable such as:

/org/jp/llc/12/directors/23/profile

In this case, llc has an id value of 12 and the director an id value of 23. They will be recorded as variables as instructed by the route map set by the package using Net::API::REST

Note that this is actually not used anymore and superseded by the Net::API::REST::Endpoint package.

_find_bin( string )

Given a binary, this will search for it in the path.

_split_str( string, [ separator ] )

Given a string and an optional separator, which revert to ; by default, this helper method will split the string.

This splitting can be tricky because the separator value itself may be enclosed in the string and surrounded by parenthesis.

_try( object type, method name, @_ )

Given an object type, a method name and optional parameters, this attempts to call it.

Apache2 methods are designed to die upon error, whereas our model is based on returning undef and setting an exception with Module::Generic::Exception, because we believe that only the main program should be in control of the flow and decide whether to interrupt abruptly the execution, not some sub routines.

AUTHOR

Jacques Deguest <jack@deguest.jp>

CPAN ID: jdeguest

https://git.deguest.jp/jack/Net-API-REST

SEE ALSO

Apache2::Request, Apache2::RequestRec, Apache2::RequestUtil

COPYRIGHT & LICENSE

Copyright (c) 2018-2019 DEGUEST Pte. Ltd.

You can use, copy, modify and redistribute this package and associated files under the same terms as Perl itself.