Perl uses Nginx fastcgi environment to do web development instances _perl

Source: Internet
Author: User
Tags md5
Hello World

A simple hello world example:

Copy the code:

#! / usr / bin / env perl
use strict;
use warnings;
use CGI :: Fast;
while (my $ q = new CGI :: Fast)
{
 print $ q-> header ("text / plain");
 print "Hello World";
}

The difference from CGI is that there is an additional loop to accept the request. The CGI :: Fast object is the same as the CGI interface, and the script can also be used as a CGI script.
Setting up nginx + FastCGI environment

Perl uses the CGI :: Fast package to provide FastCGI services. This package provides two ways to start the FastCGI process. One is to directly use the services provided by the package to change the current process into a FastCGI process. To start.
Example of nginx configuration:

Copy the code:

        location / {
            fastcgi_pass 127.0.0.1:8184;
            fastcgi_param SCRIPT_FILENAME / scripts $ fastcgi_script_name;
            include fastcgi_params;
        }

After nginx is configured, use spawn-fcgi to start the previous Hello World:
Copy the code:

$ spawn-fcgi -n -a 127.0.0.1 -p 8184 -f ./main.pl

Debug support

The parameter -n was used in the previous command line, so spawn-fcgi does not fork multiple processes and blocks, allowing the user to Ctrl + C to close. The product server can remove this parameter to make full use of the server's multi-core to provide higher Number of concurrency. I previously wrote a bash script that allows services to be restarted in the event of file changes to facilitate debugging of perl programs. The code is as follows:

Copy the code:

#! / bin / bash
#PID files and scripts that need to be started
PID_FILE = service.pid
MAIN = main.pl
#Close previously started processes
term () {
    test -e $ PID_FILE || return
    pid = `cat $ PID_FILE`
    kill -s -0 $ pid || return
    echo "Terminating $ MAIN $ pid"
    rm -f $ PID_FILE
    kill $ pid
    wait $ pid
}
#FastCGI process is also closed when the current script exits
trap "term; exit" SIGINT SIGTERM
while true
do
#Close the previous process after the first startup or file changes
    term
#Start the script in no fork mode to debug and write the PID to a file
    spawn-fcgi -n -a 127.0.0.1 -p 8184 -f ./$MAIN &
    pid = $!
    echo $ pid> $ PID_FILE
    echo "My Perl service started, pid = $ pid"
#Monitoring file changes
    files = `find. -name '* .pl' -o -name '* .pm' -o -name '* .html'`
    md5 = `md5sum $ files | md5sum`
#wait for file change
    while [[`md5sum $ files | md5sum` =" $ md5 "]]
    do
        sleep 1
    done
    echo "File changes detected, restarting service"
done


The script has been tested under Mac OSX and Linux
Routing system

Web development is inseparable from routing implementations, to make specific responses to different requests.
Routing requests rely on two parts: HTTP Method and URI, so they are mainly needed for dispatch.
In CGI, you can obtain the request method and URI through the environment variables REQUEST_METHOD and REQUEST_URI.
Therefore, a simple routing system can actually be decomposed into a second-level map. Registering routes is actually putting processing functions corresponding to rules into this map, and dispatching requests are obtained from this map according to rules. , A simple example:

Copy the code:

my% routers = ();
sub not_found
{
    print "Status: 404 \ n";
    print "Content-Type: text / html \ n \ n";
    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 $ @;
}


Example using this routing system:
Copy the code:

sub index
{
    my ($ q) = @_;
    print $ q-> header ('text / plain');
    print "Hello World!";
}
router :: add_rule ('GET', '/', \ & index);


Template system

Perl provides a large number of template system implementations. My personal favorite is the Template Toolkit. The documentation is also very rich.

Modify the previous index to use the template example:

Copy the code:

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;
}


The contents of the templates / index.html file are as follows:
Copy the code:

<html>
<head> <title> Demo </ title> </ head>
<body>
Hello $ {world}
</ body>
</ html>
Finish!
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.