Friday, April 24, 2015

mod_perl: How to send a custom content type along with custom_response

By default, mod_perl Apache2::Response::custom_response will use the following content-type: text/html; charset=iso-8859-1.
But, what if we want to use e.g. application/x-www-form-urlencoded; charset=utf-8 instead?

Main handler:
sub handler {
    my ($i_request_rec) = @_;

    @{$i_request_rec->pnotes}{'err_txt', 'err_content_type'} = ('appid=45465&status=-42', 'application/x-www-form-urlencoded; charset=utf-8');
    $i_request_rec->custom_response(Apache2::Const::SERVER_ERROR, '/error_vas/');
    return Apache2::Const::SERVER_ERROR;
}
Apache conf.:
<Location /error_vas/>
        SetHandler perl-script
        PerlResponseHandler Toto::ErrorVas
</Location>
ErrorVas.pm:
package Toto::ErrorVas;

use strict;
use warnings;
use Apache2::Const -compile => qw(:common :log);

sub handler {
    my ($i_request_rec) = @_;

    return Apache2::Const::NOT_FOUND unless $i_request_rec->prev;

    $i_request_rec->content_type($i_request_rec->prev->pnotes->{err_content_type});
    $i_request_rec->print($i_request_rec->prev->pnotes->{err_txt});

    return Apache2::Const::OK;
}
source: http://foertsch.name/ModPerl-Tricks/custom-content_type-with-custom_response.shtml