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:
1
2
3
4
5
6
7
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.:
1
2
3
4
<Location /error_vas/>
        SetHandler perl-script
        PerlResponseHandler Toto::ErrorVas
</Location>
ErrorVas.pm:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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