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.9.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_charset
Sets or gets the acceptable character set.
accept_type
Sets or gets the acceptable content type.
accept_version
Sets or gets the version of the api being queried. This is used in building the Content-Type
acceptable
This method parse the request header Accept
which could be, for example:
application/json, text/javascript, */*
And return a list of acceptable content types in list context, or the first content type of the list in scalar context.
acceptables
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
apr
Returns a Net::API::REST::Request::Param object used to access Apache mod_perl methods to manipulate request data.
args
Get the parameters data by calling "args" in Apache2::Request
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.
So for example, if the http request Content-type
is
Content-Type: application/json; charset=utf-8
Then, "charset" would return utf-8
See also "type" to retrieve only the content type, i.e without other information such as charset.
See also "client_api_version" which would contain the requested api version, if any.
See also charset for the charset provided, if any. For example utf-8
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; charset=utf-8
In this case, this would return 1.0
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.
For example:
application/json; charset=utf-8
See also "type" to retrieve only the content type, i.e without other information such as charset.
See also "client_api_version" which would contain the requested api version, if any.
See also charset for the charset provided, if any. For example utf-8
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.
You can set a maximum size to read by setting the attribute Net_API_REST_MAX_SIZE
in Apache configuration file.
For example:
<Directory /home/john/www>
PerlOptions +GlobalRequest
SetHandler modperl
# package inheriting from Net::API::REST
PerlResponseHandler My::API
# 2Mb upload limit
PerlSetVar Net_API_REST_MAX_SIZE 2097152
</Directory>
This is just an example and not a recommandation. Your mileage may vary.
datetime
Returns a new Net::API::REST::DateTime object.
decode( $string )
Given a url-encoded string, this returns the decoded string
This uses APR::Request XS method.
dnt
This is an abbreviation for Do not track
If available, typical value is a boolean such as 0
or 1
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.
document_uri
Get the value for the environment variable DOCUMENT_URI
.
encode( $string )
Given a string, this returns its url-encoded version
This uses APR::Request XS method.
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 (full file path) on disk corresponding to this request or response
See "filename" in Apache2::RequestRec for more information.
finfo
Get and set the finfo request record member
See "finfo" in Apache2::RequestRec for more information.
gateway_interface
Typical value returned from the environment variable GATEWAY_INTERFACE
is CGI/1.1
If an argument is provided, this will set the value.
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.
is_secure
Returns true (1) if the connection is made under ssl, i.e. of the environment variable HTTPS
is set to on
, other it returns false (0).
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.
mod_perl( "mod_perl/2.0.11" )
Returns the value for the environment variable MOD_PERL
.
If a value is provided, it will set the environment variable accordingly.
mod_perl_version
Read-only. This is based on the value returned by "mod_perl".
This returns a version object of the mod perl version being used, so you can call it like:
my $min_version = version->declare( 'v2.0.11' );
if( $req->mod_perl_version >= $min_version )
{
## ok
}
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.
param( $name )
Provided a name, this returns its equivalent value. If $name is an upload field, ie part of a multipart post data, it returns a Net::API::REST::Request::Upload object instead.
If a value is provided, this calls "param" in Net::API::REST::Request::Param providing it with the name ane value. This uses APR::Request::Param.
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.
parse_date
Alias to "parse_date" in Net::API::REST::DateTime
path
Get the value for the environment variable PATH
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 Net::API::REST::Query and return a hash reference.
query_string( query string )
Actually calls "args" in 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.
redirect_error_notes
Gets or sets the value for the environment variable REDIRECT_ERROR_NOTES
redirect_query_string
Gets or sets the value for the environment variable REDIRECT_QUERY_STRING
redirect_status
Gets or sets the value for the environment variable REDIRECT_STATUS
redirect_url
Gets or sets the value for the environment variable REQUEST_URI
referer
Returns the value of the Referer http header, if any.
remote_addr
Returns the remote host socket address as a APR::SockAddr object.
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,
remote_port( 1234 )
It returns the value for the environment variable REMOTE_PORT
or set its value with the argument provided if any.
$req->remote_port( 51234 );
print( "Remote port is: ", $req->remote_port, "\n" );
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 of "reply" in Net::API::REST, which is more powerful and versatile.
request
Returns the embedded Apache2::RequestRec object provided initially at object initiation.
request_scheme
Gets or sets the environment variable REQUEST_SCHEME
request_time
Time when the request started in second since epoch.
request_uri( URI )
This returns the current value for the environment variable REQUEST_URI
, or set its value if an argument is provided.
The uri provided by this environment variable include the path info if any.
For example, assuming you have a cgi residing in /cgi-bin/prog.cgi
and it is called with the path info /some/value
, the value returned would then be /cgi-bin/prog.cgi/some/value
script_filename( FILE PATH )
This returns the current value for the environment variable SCRIPT_FILENAME
, or set its value if an argument is provided.
For example, if the file being served resides at the uri /about.html
and your document root is /var/www
, the the value returned would be /var/www/about.html
It is noteworthy that this environment variable does not include any path info set, if any.
script_name( URI )
This returns the current value for the environment variable SCRIPT_NAME
, or set its value if an argument is provided.
For example, if the file being served resides at the uri /about.html
, the value returned would be /about.html
.
Even though the environment variable name is SCRIPT_NAME
, its value is any file being served and contrary to what you might believe, it is not limited to a script, such as a program.
script_uri( URI )
This returns the current value for the environment variable SCRIPT_URI
, or set its value if an argument is provided.
It is similar to "request_uri", except this returns a full uri including the protocol and host name. For example: https://example.com/cgi-bin/prog.cgi/path/info
script_url( URL )
This returns the current value for the environment variable SCRIPT_URL
, or set its value if an argument is provided.
The value returned is identical to that of "request_uri", i.e, for example: /cgi-bin/prog.cgi/path/info
server
Get the Apache2::ServerRec object for the server the request $r is running under.
server_addr( IP ADDRESS )
This returns the current value for the environment variable SERVER_ADDR
, or set its value if an argument is provided.
Typical value is an ip address.
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_protocol( "HTTP/1.1" )
This returns the current value for the environment variable SERVER_PROTOCOL
, or set its value if an argument is provided.
Typical value is HTTP/1.1
server_signature( STRING )
This returns the current value for the environment variable SERVER_SIGNATURE
, or set its value if an argument is provided.
The value of this environment variable can be empty if the Apache configuration parameter ServerSignature
is set to Off
server_software( STRING )
This returns the current value for the environment variable SERVER_SOFTWARE
, or set its value if an argument is provided.
This is typically something like Apache/2.4.41 (Ubuntu)
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 "client_socket" in 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.
str2datetime
Alias to "str2datetime" in Net::API::REST::DateTime
str2time
Alias to "str2time" in Net::API::REST::DateTime
subnet_of( $ip, $mask )
Provided with an ip address (v4 or v6), and optionally a subnet mask, and this will return a boolean value indicating if the current connection ip address is part of the provided subnet.
The mask can be a string or a number of bits.
It uses APR::IpSubnet and performs the test using the object from APR::SockAddr as provided with "remote_addr"
my $ok = $r->subnet_of( '127.0.0.1' );
my $ok = $r->subnet_of( '::1' );
my $ok = $r->subnet_of( '127.0.0.1', '255.0.0.0' );
my $ok = $r->subnet_of( '127.0.0.1', 15 );
if( !$r->subnet_of( '127.0.0.1' ) )
{
print( "Sorry, only local connections allowed\n" );
}
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
time2datetime
Alias to "time2datetime" in Net::API::REST::DateTime
time2str
Alias to "time2str" in Net::API::REST::DateTime
type
Returns the content type of the request received. This value is set at object initiation phase.
So for example, if the http request Content-type
is
Content-Type: application/json; charset=utf-8
Then, "type" would return application/json
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
uploads
Returns an array reference of Net::API::REST::Request::Upload objects.
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()>
url_decode( $string )
This is merely a convenient pointer to "decode"
url_encode( $string )
This is merely a convenient pointer to "encode"
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://gitlab.com/jackdeguest/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.