Net::API::REST::Request - Apache2 Incoming Request Access and Manipulation
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 );
v0.9.3
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.
Apache2
Fo its alter ego to manipulate outgoing http response, use the Net::API::REST::Response module.
This initiates the package and take the following parameters:
This is a required parameter to be sent with a value set to a Apache2::RequestRec object
If true, it will not perform the initialisation it would usually do under modperl.
Optional. If set with a positive integer, this will activate verbose debugging message
Tells whether the connection has been aborted or not
Returns the http Accept header value, such as text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept
text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Sets or gets the acceptable character set.
Sets or gets the acceptable content type.
Sets or gets the version of the api being queried. This is used in building the Content-Type
Content-Type
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.
Returns the http Accept-Encoding header value
Accept-Encoding
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
Accept-Language
en-GB,fr-FR;q=0.8,fr;q=0.6,ja;q=0.4,en;q=0.2
Returns the allowed methods, such as GET, POST, PUT, OPTIONS, HEAD, etc
Returns a Net::API::REST::Request::Param object used to access Apache mod_perl methods to manipulate request data.
Get the parameters data by calling "args" in Apache2::Request
Returns the http request as a string
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".
authorization
Returns the authentication type
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.
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.
param
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
Content-Type: application/json; charset=utf-8
Then, "charset" would return utf-8
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
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.
Terminate the current worker process as soon as the current request is over.
See Apache::RequestUtil for more information.
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
1.0
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.
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 );
Returns a Apache2::Connection object.
Returns the connection id; unique at any point in time. See Apache2::Connection for more information.
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.
$req-
Returns the value of the Content-Encoding HTTP response header
Content-Encoding
Retrieves the value of the Content-Language HTTP header
Content-Language
Returns the length in byte of the request body.
Retrieves the value of the Content-type header value. See Apache2::RequestRec for more information.
For example:
application/json; charset=utf-8
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.
Returns a Net::API::REST::Cookies object acting as a jar with various methods to access, manipulate and create cookies.
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.
Net_API_REST_MAX_SIZE
<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.
Returns a new Net::API::REST::DateTime object.
Given a url-encoded string, this returns the decoded string
This uses APR::Request XS method.
This is an abbreviation for Do not track
Do not track
If available, typical value is a boolean such as 0 or 1
0
1
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.
Get the value for the environment variable DOCUMENT_URI.
DOCUMENT_URI
Given a string, this returns its url-encoded version
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.
Set-Cookie
See Apache2::RequestRec for more information.
Get/set the filename (full file path) on disk corresponding to this request or response
See "filename" in Apache2::RequestRec for more information.
Get and set the finfo request record member
See "finfo" in Apache2::RequestRec for more information.
Typical value returned from the environment variable GATEWAY_INTERFACE is CGI/1.1
GATEWAY_INTERFACE
CGI/1.1
If an argument is provided, this will set the value.
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') || [] };
Return the "Status-Line" for a given status code (excluding the HTTP-Version field).
print( $req->get_status_line( 400 ) );
will print:
400 Bad 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.
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.
Returns the list of headers as an hash reference.
Returns the list of headers as a json data
Returns the list of the headers as hash or the individual value of a header:
my $cookie = $r->headers_in->{Cookie} || '';
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
Retrieve or set the http server host name, such as www.example.com.
This is not the machine hostname.
Returns an URI object of the http host being accessed. This is created during object initiation phase.
URI
This is the same as "connection_id"()
Returns the value of the http header If-Modified-Since as a DateTime object.
DateTime
If no such header exists, it returns undef()
undef()
Returns the value of the http header If-None-Match
If-None-Match
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 );
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):
$r-
read_post()
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.
Returns a boolean value on whether the request is a HEAD request or not.
HEAD
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.
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).
HTTPS
on
Returns a JSON object with the relaxed attribute enabled so that it allows more relaxed json data.
JSON
relaxed
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.
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.
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.
Returns the length in bytes of the request body.
Used for ap_get_server_name when UseCanonicalName is set to DNS (ignores setting of HostnameLookups)
Better to use the "server_name" instead.
Return our server IP address as string.
Get the path of the <Location> section from which the current "Perl*Handler" is being called.
Returns a string.
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.
undef
To figure out whether you are inside a main request or a sub-request/internal redirect, use $r-is_initial_req>.
Get/set the current request method (e.g. "GET", "HEAD", "POST", etc.).
if a new value was passed the previous value is returned.
Returns the value for the environment variable MOD_PERL.
MOD_PERL
If a value is provided, it will set the environment variable accordingly.
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 }
Last modified time of the requested resource.
Returns a timestamp in second since epoch.
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.
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.
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.
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:
send_response_body()
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.
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.
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.
Alias to "parse_date" in Net::API::REST::DateTime
Get the value for the environment variable PATH
PATH
Get/set the PATH_INFO, what is left in the path after the URI --> filename translation.
PATH_INFO
Return a string as the current value.
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.
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.
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};
Returns the pool associated with the request as a APR::Pool object of the Apache2 connection. If you rather want access to the pool object of the Apache2 request itself, use "request", such as:
# $rest being a Net::API::REST object my $request_pool = $rest->request->request->pool; $request_pool->cleanup_register( \&cleanup );
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.
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.
Get a string identifying the protocol that the client speaks, such as HTTP/1.0 or HTTP/1.1
HTTP/1.0
HTTP/1.1
Get/set the proxyrec request record member and optionally adjust other related fields.
Valid values are: PROXYREQ_NONE, PROXYREQ_PROXY, PROXYREQ_REVERSE, PROXYREQ_RESPONSE
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.
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 });
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.
Actually calls "args" in Apache2::RequestRec behind the scene.
This get/set the request QUERY string.
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
read()
See Apache2::RequestIO for more information.
Gets or sets the value for the environment variable REDIRECT_ERROR_NOTES
REDIRECT_ERROR_NOTES
Gets or sets the value for the environment variable REDIRECT_QUERY_STRING
REDIRECT_QUERY_STRING
Gets or sets the value for the environment variable REDIRECT_STATUS
REDIRECT_STATUS
Gets or sets the value for the environment variable REQUEST_URI
REQUEST_URI
Returns the value of the Referer http header, if any.
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.
Returns the remote client host name.
Returns the ip address of the client, ie remote host making the request.
It returns a string representing an ip address,
It returns the value for the environment variable REMOTE_PORT or set its value with the argument provided if any.
REMOTE_PORT
$req->remote_port( 51234 ); print( "Remote port is: ", $req->remote_port, "\n" );
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.
message
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.
Returns the embedded Apache2::RequestRec object provided initially at object initiation.
Gets or sets the environment variable REQUEST_SCHEME
REQUEST_SCHEME
Time when the request started in second since epoch.
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
/cgi-bin/prog.cgi
/some/value
/cgi-bin/prog.cgi/some/value
This returns the current value for the environment variable SCRIPT_FILENAME, or set its value if an argument is provided.
SCRIPT_FILENAME
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
/about.html
/var/www
/var/www/about.html
It is noteworthy that this environment variable does not include any path info set, if any.
This returns the current value for the environment variable SCRIPT_NAME, or set its value if an argument is provided.
SCRIPT_NAME
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.
This returns the current value for the environment variable SCRIPT_URI, or set its value if an argument is provided.
SCRIPT_URI
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
https://example.com/cgi-bin/prog.cgi/path/info
This returns the current value for the environment variable SCRIPT_URL, or set its value if an argument is provided.
SCRIPT_URL
The value returned is identical to that of "request_uri", i.e, for example: /cgi-bin/prog.cgi/path/info
/cgi-bin/prog.cgi/path/info
Get the Apache2::ServerRec object for the server the request $r is running under.
This returns the current value for the environment variable SERVER_ADDR, or set its value if an argument is provided.
SERVER_ADDR
Typical value is an ip address.
Returns the server admin as provided by Apache2::ServerRec
Returns the server host name as provided by Apache2::ServerRec
Get the current request's server name
Get the current server port
This returns the current value for the environment variable SERVER_PROTOCOL, or set its value if an argument is provided.
SERVER_PROTOCOL
Typical value is HTTP/1.1
This returns the current value for the environment variable SERVER_SIGNATURE, or set its value if an argument is provided.
SERVER_SIGNATURE
The value of this environment variable can be empty if the Apache configuration parameter ServerSignature is set to Off
ServerSignature
Off
This returns the current value for the environment variable SERVER_SOFTWARE, or set its value if an argument is provided.
SERVER_SOFTWARE
This is typically something like Apache/2.4.41 (Ubuntu)
Apache/2.4.41 (Ubuntu)
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 );
Set a list of handlers to be called for a given phase. Any previously set handlers are forgotten.
$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 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.
Get/set the client socket and returns a APR::Socket object.
This calls "client_socket" in Apache2::Connection package.
Get/set the reply status for the client request.
Normally you would use some Apache2::Const constant, e.g. Apache2::Const::REDIRECT.
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.:
Apache2::Const:OK
$r->status( $some_code ); return( Apache2::Const::OK );
See also $r-status_line>, which. if set, overrides $r-status>.
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.
200 Document follows
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:
status_line()
$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.
Alias to "str2datetime" in Net::API::REST::DateTime
Alias to "str2time" in Net::API::REST::DateTime
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" ); }
Get/set the Apache subprocess_env table, or optionally set the value of a named entry.
subprocess_env
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 -->
Get or set the first HTTP request header as a string. For example:
GET /foo/bar/my_path_info?args=3 HTTP/1.0
Alias to "time2datetime" in Net::API::REST::DateTime
Alias to "time2str" in Net::API::REST::DateTime
Returns the content type of the request received. This value is set at object initiation phase.
Then, "type" would return application/json
application/json
The URI without any parsing performed.
If for example the request was:
"$r->uri" returns:
/foo/bar/my_path_info
whereas "$r->unparsed_uri" returns:
/foo/bar/my_path_info?args=3
Returns an array reference of Net::API::REST::Request::Upload objects.
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()>
This is merely a convenient pointer to "decode"
This is merely a convenient pointer to "encode"
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 );
Returns the user agent, ie the browser signature as provided in the request headers received under the http header User-Agent
User-Agent
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.
Given a binary, this will search for it in the path.
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.
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.
Jacques Deguest <jack@deguest.jp>
CPAN ID: jdeguest
https://gitlab.com/jackdeguest/Net-API-REST
Apache2::Request, Apache2::RequestRec, Apache2::RequestUtil
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.
To install Net::API::REST, copy and paste the appropriate command in to your terminal.
cpanm
cpanm Net::API::REST
CPAN shell
perl -MCPAN -e shell install Net::API::REST
For more information on module installation, please visit the detailed CPAN module installation guide.