user7445564
user7445564

Reputation:

Mojolicious in Apache mod_perl

i've got an ~15year old Perl-Application. The application runs on Apache, example-code looks like:

use Apache2::RequestUtil ();
use Apache2::RequestRec ();
use Apache2::Const -compile => qw(OK);

sub handler {
  my $r = shift;
  Apache2::RequestUtil->request($r)                                     
  $r->subprocess_env;                      

  $r = Apache2::RequestUtil->request; 

  $r->content_type("text/html");
  $r->print("Hello World");
  };

 return Apache2::Const::OK;              
}
1;

This works, but now I want to use Mojolicious for my new functionalily of this application. But how can I integrate Mojolicious to this app? When I do the following

    use Apache2::RequestUtil ();
use Apache2::RequestRec ();
use Apache2::Const -compile => qw(OK);

sub handler {
  my $r = shift;
  Apache2::RequestUtil->request($r                                     
  $r->subprocess_env;                      

  $r = Apache2::RequestUtil->request; 

  get '/:foo' => sub {
    my $self = shift;
    my $foo  = $self->param('foo');
    $self->render(text => "Hello from $foo.");
  };

 return Apache2::Const::OK;              
}
app->start;
1;

I get a blank page. Is it possible to integrate Mojo to my app at all?

Upvotes: 4

Views: 1890

Answers (1)

Helmut Wollmersdorfer
Helmut Wollmersdorfer

Reputation: 451

If you want the benefits of Mojolicious you should not use Apache requests directly.

First you need a special virtual host configuration. See https://github.com/kraih/mojo/wiki/Apache-deployment and scroll down to the chapter Apache/mod_perl (PSGI/Plack). I authored this chapter, because I run a dozen of Mojo applications under mod_perl and it was a bit of trial and error to find a working way.

Here the Apache config file as an example:

<VirtualHost *:80>
  ServerName myapp.local
  DocumentRoot /home/sri/myapp

  PerlOptions +Parent

  <Perl>
    $ENV{PLACK_ENV} = 'production';
    $ENV{MOJO_HOME} = '/home/sri/myapp';
    $ENV{MOJO_MODE} = 'deployment';
  </Perl>

  <Location />
    SetHandler perl-script
    PerlResponseHandler Plack::Handler::Apache2
    PerlSetVar psgi_app /home/sri/myapp/script/myapp
  </Location>
</VirtualHost>

Second your module MyApp.pm should look like this:

package MyApp;
use Mojo::Base 'Mojolicious';

sub startup {
  my $app = shift;

  my $routes = $app->routes;

  $routes->get('/:foo' => sub {
    my $self = shift;
    my $foo  = $self->param('foo');
    $self->render(text => "Hello from $foo.");
  });

}

1;

That's all you need. The Plack::Handler::Apache2 builds a layer between mod_perl and Mojolicious. Of course you need a script myapp. This script also allows you to run the web application from the console of your desktop e. g. during development and testing.

Upvotes: 9

Related Questions