NAME
Net::API::REST::Response - Apache2 Outgoing Response Access and Manipulation
SYNOPSIS
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 );
VERSION
v0.4.14
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
- debug
-
Optional. If set with a positive integer, this will activate verbose debugging message
allow_credentials
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials
allow_headers
Sets the Access-Control-Allow-Headers
header.
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Headers
allow_methods
Sets the Access-Control-Allow-Methods
header.
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Methods
allow_origin
Sets the Access-Control-Allow-Origin
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin
alt_svc
Sets the Alt-Svc
header.
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Alt-Svc
bytes_sent()
The number of bytes sent to the client, handy for logging, etc.
cache_control
Sets the Cache-Control
header.
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control
clear_site_data
Sets the Clear-Site-Data
header.
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Clear-Site-Data
code( integer )
Get/set the reply status for the client request.
Normally you would use some Apache2::Const constant, e.g. Apache2::Const::REDIRECT.
connection()
Returns a Apache2::Connection object.
content_disposition
Sets the Content-Disposition
header.
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition
content_encoding( string )
Get/set content encoding (the Content-Encoding
HTTP header). Content encodings are string like gzip
or 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" ) );
content_language()
Returns the http header value for Content-Language
content_languages( string )
Get/set content languages (the Content-Language
HTTP header). Content languages are string like en
or fr
.
It returns the current list of content languages, as an array reference.
content_length( integer )
Set the content length for this request.
See Apache2::Response for more information.
content_location
Sets the Content-Location
header.
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Location
content_range
Sets the Content-Range
header.
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range
content_security_policy
Sets the Content-Security-Policy
header.
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy
content_security_policy_report_only
Sets the Content-Security-Policy-Report-Only
header.
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy-Report-Only
content_type( mime_type )
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.
cookie_new( hash reference )
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.
- name
- value
- domain
- expires
- http_only
- max_age
- path
- secure
- same_site
cookie_replace( cookie object )
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.
cookie_set( cookie object )
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.
cross_origin_embedder_policy
Sets the Cross-Origin-Embedder-Policy
header
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Embedder-Policy
cross_origin_opener_policy
Sets the Cross-Origin-Opener-Policy
header.
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Opener-Policy
cross_origin_resource_policy
Sets the Cross-Origin-Resource-Policy
header.
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Resource-Policy
cspro
Alias for "content_security_policy_report_only"
custom_response()
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
)
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
decode( $string )
Given a url-encoded string, this returns the decoded string
This uses APR::Request XS method.
digest
Sets the Digest
header.
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Digest
encode( $string )
Given a string, this returns its url-encoded version
This uses APR::Request XS method.
env( name, [ name => value ] )
Get or set an environment variable.
err_headers( name => value, [ name2 => value2, etc ] )
Given one or more name => value pair, this will set them in the http header using the err_headers_out method.
err_headers_out()
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.
escape
Provided with a value and this will return it uri escaped by calling "uri_escape" in URI::Escape.
etag( string )
Sets the Etag
http header.
expires
Sets the expires
header.
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Expires
expose_headers
Sets the Access-Control-Expose-Headers
header.
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()
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.
get_http_message( integer, [ language ] )
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.
get_status_line( integer )
Return the Status-Line
for a given status code (excluding the HTTP-Version field).
If an invalid or unknown status code is passed, 500 Internal Server Error
will be returned.
For example:
print( $res->get_status_line( 400 ) );
will print: 400 Bad Request
headers( [ name, [ name => value ] )
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.
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
internal_redirect( URI object | uri path )
Given a URI
object or a uri path string, this redirect the current request to some other uri internally.
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.
internal_redirect_handler( URI object | uri path string )
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.
is_info( integer )
Given a http code integer, this will return true if the code is comprised between 100 and less than 200, false otherwise.
is_success( integer )
Given a http code integer, this will return true if the code is comprised between 200 and less than 300, false otherwise.
is_redirect( integer )
Given a http code integer, this will return true if the code is comprised between 300 and less than 400, false otherwise.
is_error( integer )
Given a http code integer, this will return true if the code is comprised between 400 and less than 600, false otherwise.
is_client_error( integer )
Given a http code integer, this will return true if the code is comprised between 400 and less than 500, false otherwise.
is_server_error( integer )
Given a http code integer, this will return true if the code is comprised between 500 and less than 600, false otherwise.
keep_alive
Sets the Keep-Alive
header.
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Keep-Alive
last_modified
Sets the Last-Modified
header.
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Last-Modified
last_modified_date( http datetime )
Get or set the http datetime for the http header Last-Modified-Date
location
Sets the Location
header.
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Location
lookup_uri( URI object | uri path string, [ handler ] )
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 );
See Apache2::SubRequest for more information.
make_etag( boolean )
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 );
max_age
Sets the Access-Control-Max-Age
header.
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Max-Age
meets_conditions()
Implements condition GET
rules for HTTP/1.1 specification. This function inspects the client headers and determines if the response fulfills the specified requirements.
$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).
nel
Sets the NEL
header.
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/NEL
no_cache( boolean )
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.
This method should be invoked before any response data has been sent out.
print( list of data )
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.
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.
printf( format, list )
Format and send data to the client (same as "printf").
$cnt = $res->printf( $format, @args );
It returns how many bytes were sent (or buffered).
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.
redirect( URI object | full uri string )
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/" ) );
referrer_policy
Sets the Referrer-Policy
header.
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy
request()
Returns the Net::API::REST::Request object.
retry_after
Sets the Retry-After
header.
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After
rflush()
Flush any buffered data to the client.
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.
send_cgi_header()
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).
See Apache2::Response for more information.
sendfile( filepath, [ offset, length ] )
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
server
Sets the Server
header.
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Server
server_timing
Sets the Server-Timing
header.
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Server-Timing
set_content_length( integer )
Set the content length for this request.
$res->set_content_length( $length );
It does not return any value.
set_cookie
Sets the Set-Cookie
header.
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie
set_last_modified( timestamp in seconds )
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_keepalive()
Set the keepalive status for this request.
$ret = $res->set_keepalive();
It returns true if keepalive can be set, false otherwise.
socket()
Get/set the client socket and returns a APR::Socket object.
This calls the client_socket method of the Apache2::Connection package.
sourcemap
Sets the SourceMap
header.
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/SourceMap
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>.
strict_transport_security
Sets the Strict-Transport-Security
header.
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security
timing_allow_origin
Sets the Timing-Allow-Origin
header.
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Timing-Allow-Origin
trailer
Sets the Trailer
header.
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Trailer
transfer_encoding
Sets the Transfer-Encoding
header.
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Transfer-Encoding
unescape
Unescape the given data chunk by calling "uri_unescape" in URI::Escape
update_mtime( timestamp in seconds )
Set the $res-
mtime> field to the specified value if it's later than what's already there.
$res->update_mtime( $mtime );
upgrade
Sets the Upgrade
header.
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Upgrade
uri_escape
Provided with a string and this uses URI::Escape to return an uri-escaped string.
uri_unescape
Provided with an uri-escaped string and this will decode it and return its original string.
url_decode
Provided with an url-encoded string and this will return its decoded version.
url_encode
Provided with a string and this will return an url-encoded version.
vary
Sets the Vary
header.
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Vary
via
Sets the Via
header.
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Via
want_digest
Sets the Want-Digest
header.
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Want-Digest
warning
Sets the Warning
header.
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Warning
write()
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.
www_authenticate
Sets the WWW-Authenticate
header.
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/WWW-Authenticate
x_content_type_options
Sets the X-Content-Type-Options
header.
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Content-Type-Options
x_dns_prefetch_control
Sets the X-DNS-Prefetch-Control
header.
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-DNS-Prefetch-Control
x_frame_options
Sets the X-Frame-Options
header.
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options
x_xss_protection
Sets the X-XSS-Protection
header.
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-XSS-Protection
_request()
Returns the embedded Apache2::RequestRec
_set_get_multi
$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.
_set_get_one
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.
_try( object accessor, method, [ arguments ] )
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.