Net::API::REST::Response - Apache2 Outgoing Response Access and Manipulation
use Net::API::REST::Response; ## $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.4.14
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
Optional. If set with a positive integer, this will activate verbose debugging message
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials
Sets the Access-Control-Allow-Headers header.
Access-Control-Allow-Headers
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Headers
Sets the Access-Control-Allow-Methods header.
Access-Control-Allow-Methods
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Methods
Sets the Access-Control-Allow-Origin
Access-Control-Allow-Origin
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin
Sets the Alt-Svc header.
Alt-Svc
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Alt-Svc
The number of bytes sent to the client, handy for logging, etc.
Sets the Cache-Control header.
Cache-Control
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control
Sets the Clear-Site-Data header.
Clear-Site-Data
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Clear-Site-Data
Get/set the reply status for the client request.
Normally you would use some Apache2::Const constant, e.g. Apache2::Const::REDIRECT.
Returns a Apache2::Connection object.
Sets the Content-Disposition header.
Content-Disposition
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition
Get/set content encoding (the Content-Encoding HTTP header). Content encodings are string like gzip or compress.
Content-Encoding
gzip
compress
For example, here is how to send a gzip'ed response:
require Compress::Zlib; $res->content_type( "text/plain" ); $res->content_encoding( "gzip" ); $res->print( Compress::Zlib::memGzip( "some text to be gzipped" ) );
Returns the http header value for Content-Language
Content-Language
Get/set content languages (the Content-Language HTTP header). Content languages are string like en or fr.
en
fr
It returns the current list of content languages, as an array reference.
Set the content length for this request.
See Apache2::Response for more information.
Sets the Content-Location header.
Content-Location
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Location
Sets the Content-Range header.
Content-Range
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range
Sets the Content-Security-Policy header.
Content-Security-Policy
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy
Sets the Content-Security-Policy-Report-Only header.
Content-Security-Policy-Report-Only
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy-Report-Only
Get/set the HTTP response Content-type header value.
For example, set the "Content-type" header to text/plain.
$res->content_type('text/plain');
If you set this header via the headers_out table directly, it will be ignored by Apache. So do not do that.
headers_out
Given a hash reference with the following properties, this will create a Net::API::REST::Cookie object that can be stringified and aded into a Set-Cookie http header.
Set-Cookie
Given a cookie object, this either sets the given cookie in a Set-Cookie header or replace the existing one with the same cookie name, if any.
It returns the cookie object provided.
Given a cookie object, this set the Set-Cookie http header for this cookie.
However, it does not check if another Set-Cookie header exists for this cookie.
Sets the Cross-Origin-Embedder-Policy header
Cross-Origin-Embedder-Policy
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Embedder-Policy
Sets the Cross-Origin-Opener-Policy header.
Cross-Origin-Opener-Policy
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Opener-Policy
Sets the Cross-Origin-Resource-Policy header.
Cross-Origin-Resource-Policy
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Resource-Policy
Alias for "content_security_policy_report_only"
Install a custom response handler for a given status.
$res->custom_response( $status, $string );
The first argument is the status for which the custom response should be used (e.g. Apache2::Const::AUTH_REQUIRED)
Apache2::Const::AUTH_REQUIRED
The second argument is the custom response to use. This can be a static string, or a URL, full or just the uri path (/foo/bar.txt).
custom_response() does not alter the response code, but is used to replace the standard response body. For example, here is how to change the response body for the access handler failure:
package MyApache2::MyShop; use Apache2::Response (); use Apache2::Const -compile => qw(FORBIDDEN OK); sub access { my $r = shift; if (MyApache2::MyShop::tired_squirrels()) { $r->custom_response(Apache2::Const::FORBIDDEN, "It's siesta time, please try later"); return Apache2::Const::FORBIDDEN; } return Apache2::Const::OK; } ... # httpd.conf PerlModule MyApache2::MyShop <Location /TestAPI__custom_response> AuthName dummy AuthType none PerlAccessHandler MyApache2::MyShop::access PerlResponseHandler MyApache2::MyShop::response </Location>
When squirrels can't run any more, the handler will return 403, with the custom message:
It's siesta time, please try later
Given a url-encoded string, this returns the decoded string
This uses APR::Request XS method.
Sets the Digest header.
Digest
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Digest
Given a string, this returns its url-encoded version
Get or set an environment variable.
Given one or more name => value pair, this will set them in the http header using the err_headers_out method.
Get/set MIME response headers, printed even on errors and persist across internal redirects.
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:
$res->err_headers_out->add('Set-Cookie' => $cookie); return( Apache2::Const::NOT_FOUND );
If the handler does:
$res->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.
Provided with a value and this will return it uri escaped by calling "uri_escape" in URI::Escape.
Sets the Etag http header.
Etag
Sets the expires header.
expires
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Expires
Sets the Access-Control-Expose-Headers header.
Access-Control-Expose-Headers
e.g.: Access-Control-Expose-Headers: Content-Encoding, X-Kuma-Revision
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Headers
Flush any buffered data to the client.
$res->flush();
Unless STDOUT stream's $| is false, data sent via $req-print()> is buffered. This method flushes that data to the client.
$req-
Given an http code integer, and optionally a language code, this returns the http status message in the language given.
If no language is provided, this returns the message in en_GB, i.e. British English.
en_GB
Return the Status-Line for a given status code (excluding the HTTP-Version field).
Status-Line
If an invalid or unknown status code is passed, 500 Internal Server Error will be returned.
500 Internal Server Error
For example:
print( $res->get_status_line( 400 ) );
will print: 400 Bad Request
400 Bad Request
If a name => value pair is provided, this will set the corresponding http header.
If only a name is provided, this will retrieve the corresponding http header value and return it.
If nothing is provided, it will return the http headers as a hash reference.
It uses the Apache2 err_headers_out method in the background.
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
Given a URI object or a uri path string, this redirect the current request to some other uri internally.
URI
If a URI object is given, its path method will be used to get the path string.
$res->internal_redirect( $new_uri );
In case that you want some other request to be served as the top-level request instead of what the client requested directly, call this method from a handler, and then immediately return Apache2::Const::OK. The client will be unaware the a different request was served to her behind the scenes.
See Apache2::SubRequest for more information.
Identical to internal_redirect, plus automatically sets $res-content_type> is of the sub-request to be the same as of the main request, if $res-handler> is true.
$res-
Given a http code integer, this will return true if the code is comprised between 100 and less than 200, false otherwise.
Given a http code integer, this will return true if the code is comprised between 200 and less than 300, false otherwise.
Given a http code integer, this will return true if the code is comprised between 300 and less than 400, false otherwise.
Given a http code integer, this will return true if the code is comprised between 400 and less than 600, false otherwise.
Given a http code integer, this will return true if the code is comprised between 400 and less than 500, false otherwise.
Given a http code integer, this will return true if the code is comprised between 500 and less than 600, false otherwise.
Sets the Keep-Alive header.
Keep-Alive
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Keep-Alive
Sets the Last-Modified header.
Last-Modified
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Last-Modified
Get or set the http datetime for the http header Last-Modified-Date
Last-Modified-Date
Sets the Location header.
Location
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location
Create a sub request from the given URI. This sub request can be inspected to find information about the requested URI.
$ret = $res->lookup_uri( $new_uri ); $ret = $res->lookup_uri( $new_uri, $next_filter );
Construct an entity tag from the resource information. If it's a real file, build in some of the file characteristics.
$etag = $res->make_etag( $force_weak );
Sets the Access-Control-Max-Age header.
Access-Control-Max-Age
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Max-Age
Implements condition GET rules for HTTP/1.1 specification. This function inspects the client headers and determines if the response fulfills the specified requirements.
GET
$status = $res->meets_conditions();
It returns Apache2::Const::OK if the response fulfils the condition GET rules. Otherwise some other status code (which should be returned to Apache).
Sets the NEL header.
NEL
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/NEL
Add/remove cache control headers:
$prev_no_cache = $res->no_cache( $boolean );
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.
no_cache
This method should be invoked before any response data has been sent out.
Send data to the client.
$cnt = $res->print( @msg );
It returns how many bytes were sent (or buffered). If zero bytes were sent, print will return 0E0, or zero but true, which will still evaluate to 0 in a numerical context.
zero but true
The data is flushed only if STDOUT stream's $| is true. Otherwise it's buffered up to the size of the buffer, flushing only excessive data.
Format and send data to the client (same as "printf").
$cnt = $res->printf( $format, @args );
It returns how many bytes were sent (or buffered).
Given an URI, this will prepare the http headers and return the proper code for a 301 temporary http redirect.
It should be used like this in your code:
return( $res->redirect( "https://example.com/somewhere/" ) );
Sets the Referrer-Policy header.
Referrer-Policy
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy
Returns the Net::API::REST::Request object.
Sets the Retry-After header.
Retry-After
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After
Unless STDOUT stream's $| is false, data sent via $res-print()> is buffered. This method flushes that data to the client.
It does not return any value.
Parse the header.
$res->send_cgi_header( $buffer );
This method is really for back-compatibility with mod_perl 1.0. It's very inefficient to send headers this way, because of the parsing overhead.
If there is a response body following the headers it'll be handled too (as if it was sent via print()).
Notice that if only HTTP headers are included they won't be sent until some body is sent (again the send part is retained from the mod_perl 1.0 method).
send
Send a file or a part of it
$rc = $req->sendfile( $filename ); $rc = $req->sendfile( $filename, $offset ); $rc = $req->sendfile( $filename, $offset, $len );
It returns a APR::Const constant.
On success, APR::Const::SUCCESS is returned.
In case of a failure -- a failure code is returned, in which case normally it should be returned to the caller
Sets the Server header.
Server
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Server
Sets the Server-Timing header.
Server-Timing
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Server-Timing
$res->set_content_length( $length );
Sets the Set-Cookie header.
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie
Sets the Last-Modified response header field to the value of the mtime field in the request structure -- rationalized to keep it from being in the future.
$res->set_last_modified( $mtime );
If the $mtime argument is passed, $r->update_mtime will be first run with that argument.
Set the keepalive status for this request.
$ret = $res->set_keepalive();
It returns true if keepalive can be set, false otherwise.
Get/set the client socket and returns a APR::Socket object.
This calls the client_socket method of the Apache2::Connection package.
Sets the SourceMap header.
SourceMap
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/SourceMap
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.:
Apache2::Const:OK
$r->status( $some_code ); return( Apache2::Const::OK );
See also $r-status_line>, which. if set, overrides $r-status>.
$r-
Sets the Strict-Transport-Security header.
Strict-Transport-Security
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security
Sets the Timing-Allow-Origin header.
Timing-Allow-Origin
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Timing-Allow-Origin
Sets the Trailer header.
Trailer
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Trailer
Sets the Transfer-Encoding header.
Transfer-Encoding
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Transfer-Encoding
Unescape the given data chunk by calling "uri_unescape" in URI::Escape
Set the $res-mtime> field to the specified value if it's later than what's already there.
$res->update_mtime( $mtime );
Sets the Upgrade header.
Upgrade
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Upgrade
Provided with a string and this uses URI::Escape to return an uri-escaped string.
Provided with an uri-escaped string and this will decode it and return its original string.
Provided with an url-encoded string and this will return its decoded version.
Provided with a string and this will return an url-encoded version.
Sets the Vary header.
Vary
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Vary
Sets the Via header.
Via
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Via
Sets the Want-Digest header.
Want-Digest
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Want-Digest
Sets the Warning header.
Warning
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Warning
Send partial string to the client
$cnt = $req->write( $buffer ); $cnt = $req->write( $buffer, $len ); $cnt = $req->write( $buffer, $len, $offset );
See Apache2::RequestIO for more information.
Sets the WWW-Authenticate header.
WWW-Authenticate
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/WWW-Authenticate
Sets the X-Content-Type-Options header.
X-Content-Type-Options
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Content-Type-Options
Sets the X-DNS-Prefetch-Control header.
X-DNS-Prefetch-Control
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-DNS-Prefetch-Control
Sets the X-Frame-Options header.
X-Frame-Options
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options
Sets the X-XSS-Protection header.
X-XSS-Protection
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-XSS-Protection
Returns the embedded Apache2::RequestRec
$self->_set_get_multi( 'SomeHeader' => $some_value );
Sets or gets a header with multiple values. The value provided for the header can be either an array reference and it will be used as is (after being copied), or a regular string, which will be converted into an array reference by splitting it by comma.
If the value is undefined, it will remove the corresponding header.
$self->_set_get_multi( 'SomeHeader' => undef() );
If no value is provided, it returns the current value for this header as a Module::Generic::Array object.
Sets or gets a header with the provided value. If the value is undefined, the header will be removed.
If no value is provided, it returns the current value as an array object (Module::Generic::Array) or as a scalar object (Module::Generic::Scalar) if it is not a reference.
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.
undef
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.