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.10
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
bytes_sent()
The number of bytes sent to the client, handy for logging, etc.
connection()
Returns a Apache2::Connection object.
code( integer )
Get/set the reply status for the client request.
Normally you would use some Apache2::Const constant, e.g. Apache2::Const::REDIRECT.
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_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.
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
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.
etag( string )
Sets the Etag
http header.
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.
last_modified_date( http datetime )
Get or set the http datetime for the http header Last-Modified-Date
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 );
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).
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/" ) );
request()
Returns the Net::API::REST::Request object.
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
set_content_length( integer )
Set the content length for this request.
$res->set_content_length( $length );
It does not return any value.
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.
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>.
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 );
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.
_request()
Returns the embedded Apache2::RequestRec
_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://git.deguest.jp/jack/Net-API-REST
SEE ALSO
Apache2::Request, Apache2::RequestRec, Apache2::RequestUtil
COPYRIGHT & LICENSE
Copyright (c) 2018-2019 DEGUEST Pte. Ltd.
You can use, copy, modify and redistribute this package and associated files under the same terms as Perl itself.