Perl使用nginx FastCGI环境做WEB开发实例

2019-10-01 11:50:15王振洲

    echo "File changes detected, restarting service"
done
该脚本已在Mac OSX和Linux下测试通过

路由系统

做Web开发离不开路由实现,来对不同请求来做出特定的响应。
路由请求依赖HTTP Method和URI两部分,因此主要就是需要这两者来做分派。
在CGI中可以通过环境变量REQUEST_METHOD和REQUEST_URI来获取请求方法和URI。
因此一个简单的路由系统实际上可以分解为一个二级的map,注册路由实际上就是往这个map里放入规则对应的处理函数,而分派请求则是从这个map里根据规则获取对应的处理函数,一个简单的例子:

my %routers = ();

sub not_found
{
    print "Status: 404n";
    print "Content-Type: text/htmlnn";
    print<<EOF
<html>
<body>
<h1>404 Not found</h1>
Cannot find $ENV{REQUEST_PATH}.
</body>
</html>
EOF
}


sub add_rule
{
    my ($method, $path, $callback) = @_;
    my $handlers = $routers{$method};
    $handlers = $routers{$method} = {} if not $handlers;
    $handlers->{$path} = $callback;
}

sub dispatch
{
    my $q = shift;
    my $method = $ENV{REQUEST_METHOD};
    my $uri = $ENV{REQUEST_URI};
    $uri =~ s/?.*$//;
    my $handler = ($routers{$method} || {})->{$uri} || not_found;
    eval
    {
 &$handler($q);
    };
    print STDERR "Failed to handle $method $uri: $@n" if $@;
}
使用这个路由系统的例子:

sub index
{
    my ($q) = @_;
    print $q->header('text/plain');
    print "Hello World!";
}

router::add_rule('GET', '/', &index);


模板系统

perl提供了大量的模板系统的实现,我个人最喜欢的是Template Toolkit,文档也非常丰富,网站是 http://www.template-toolkit.org/ 。

将前面的index修改为使用模板的例子:

use Template;

my $tt = new Template({INCLUDE_PATH => 'templates', INTERPOLATE => 1});

sub index
{
    my ($q) = @_;
    my $output = '';
    print $q->header('text/html');

    $tt->process('index.html', {world => 'World'}, $output) || die $tt->error();
    print $output;
}
其中templates/index.html文件内容如下:

<html>
<head><title>Demo</title></head>
<body>
Hello ${world}
</body>
</html>

完!