mod_perl handler skeltons

29 02 2008

Because I rarely write mod_perl handler from scratch, tend to forget very basics of how it should be.Note “bare minimum” mod_perl response handlers here so that I can quickly start writing handlers from copying it.

Suppose installation of Apache 2.2, mod_perl and libapreq2 is successfully finished.

Apache configuration

LoadModule perl_module lib/httpd/mod_perl.so
LoadModule apreq_module lib/httpd/mod_apreq2.so

PerlSwitches -Mlib=/home/www

<Location /hello>
    SetHandler perl-script
    PerlResponseHandler My::Hello
</Location>

<Location /handler>
    SetHandler perl-script
    PerlResponseHandler My::Handler
</Location>

static handler

In /home/www/My/Hello.pm,

package My::Hello;
use strict; use Apache2::RequestRec;
use Apache2::RequestIO;
use Apache2::Const -compile => 'OK';

sub handler : method {
    my ($class, $r) = @_;
    $r->content_type('text/plain');
    print 'Hello, world';
    return Apache2::Const::OK;
}
1;

http://localhost/hello should return ‘Hello, world’.

Dealing with parameters

In /home/www/My/Handler.pm,

package My::Handler;
use strict;

use Apache2::RequestRec;
use Apache2::RequestIO;
use Apache2::Request;
use Apache2::Const -compile => 'OK';

sub handler : method {
    my ($class, $r) = @_;

    $r->content_type('text/plain');

    my $req = Apache2::Request->new($r);
    print $req->param('test1');

    return Apache2::Const::OK;
}

1;

Should take parameter from query like http://localhost/handler?test1=Hello or form like below.

<form action="/handler" method="POST">
<input type="text" name="test1">
<br>
<input type="submit">
</form>