[Catalyst] Handling a path of '/'

Bill Moseley moseley at hank.org
Fri Dec 2 04:26:00 CET 2005


On Thu, Dec 01, 2005 at 09:16:13PM -0600, Justin Guenther wrote:
> > -----Original Message-----
> > From: catalyst-bounces at lists.rawmode.org 
> > [mailto:catalyst-bounces at lists.rawmode.org] On Behalf Of Bill Moseley
> > Sent: December 1, 2005 9:07 PM
> > To: The elegant MVC web framework
> > Subject: Re: [Catalyst] Handling a path of '/'
> > 
> > I just use default() in my App class for handling "/".  Any 
> > reason why using using Index or Path would be better?
> 
> I opted not to use default() for this since I wanted to be able to serve out
> 404 error pages for invalid paths.

Why couldn't you do that?

I just set $c->res->status( 404 ) and my end sub sees that and uses
error.tt to generate output.

I just did this an hour ago, so it's not well tested.

sub default : Private {

    my ( $self, $c ) = @_;

    $c->res->status( 404 );  # assume the worse

    my $site = $c->config->{dirs} && $c->config->{dirs}{site}
        ? $c->config->{dirs}{site}
        : File::Spec->catfile( $c->config->{root}, 'site' );

    my $path = File::Spec->catfile( $site, $c->req->path );


    # If there's no trailing slash then see if it's a directory
    # Kind of defeats the purpose of using catfile... :P

    unless ( $c->req->uri->path =~ m!/$! ) {

        # It's a dir -- add a slash to path and redirect
        if ( -d $path ) {
            my $redirect = $c->req->uri->clone;
            $redirect->path( $redirect->path . '/' );
            return $c->res->redirect( $redirect );
        }

    } else { # uri ends in slash
        $path .= '/index.html';
    }



    return unless $c->forward('/static/serve_path', [ $path ]);


    if ( $c->res->body && $path =~ /\.html$/ ) {
        $c->stash->{template} = $c->res->body;
        $c->res->body( undef );
        # $c->res->headers->remove_content_headers;
        $c->res->headers->content_length( 0 );  # force recalc of body size
    }

}





-- 
Bill Moseley
moseley at hank.org




More information about the Catalyst mailing list