Perl + FastCGI do Web Development Learning notes

Source: Internet
Author: User


Hello World
A simple Hello World example:


The code is as follows

#!/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 with CGI is only that there is one more loop to accept the request, the Cgi::fast object is the same as the CGI interface, and the script can be used as a CGI script.



Build Nginx + FastCGI Environment
Perl uses the Cgi::fast package to provide the FASTCGI service, which provides two ways to start the fastcgi process, one that is directly using the service provided by the package to turn the current process into a fastcgi process, and the other is to start with a third-party tool spawn-fcgi.
Nginx Configuration Method Example:


The code is as follows
Location/{
Fastcgi_pass 127.0.0.1:8184;
Fastcgi_param Script_filename/scripts$fastcgi_script_name;
Include Fastcgi_params;
}


After configuring the Nginx, use spawn-fcgi to start the Hello World in front:


The code is as follows
$ spawn-fcgi-n-a 127.0.0.1-p 8184-f./main.pl


Debugging support
Parameter-n is used in the previous command line so that spawn-fcgi do not fork multiple processes and block, allowing users to CTRL + C to shut down, the product server can remove this parameter to take advantage of the server's multi-core to provide a higher number of concurrency. I wrote a bash script that allows you to restart the service in the event of a file change, to easily debug the Perl program, as follows:


The code is as follows


#!/bin/bash
#PID文件和需要启动的脚本
Pid_file=service.pid
main=main.pl


#关闭之前启动的进程
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进程
Trap "Term;exit" SIGINT sigterm
While True
Todo
#首次启动或者文件改动后都需要关闭之前的进程
Term
#以no Fork to start the script debugging and write the PID to the 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"
#监控文件变化
Files= ' Find. -name ' *.pl '-o-name ' *.pm '-o-name ' *.html '
md5= ' md5sum $files |md5sum '
#wait for file change
while [[' md5sum $files |md5sum ' = ' $md 5 ']]
Todo
Sleep 1
Done
echo "File changes detected, restarting service"


Done this script has been tested under Mac OS X and Linux through



Routing system
Web development cannot be done without routing implementations to make specific responses to different requests.
The routing request relies on both the HTTP method and the URI, so it is primarily necessary to assign the two.
In CGI, the request method and URI can be obtained through the environment variable request_method and Request_uri.
So a simple routing system can actually be decomposed into a level two map, where the registration route actually puts the corresponding handler function into the map, and the dispatch request obtains the corresponding processing function from the map according to the rule, a simple example:


The code is as follows


My%routers = ();



Sub Not_found
{
print "status:404n";
print "Content-type:text/htmlnn";
Print<<eof
<body>
Cannot find $ENV {Request_path}.
</body>
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 $@;
}



Examples of using this routing system are:


The code is as follows

Sub Index
{
My ($q) = @_;
Print $q->header (' Text/plain ');
Print "Hello world!";
}

Router::add_rule (' Get ', '/', &index);


Template system
Perl provides a lot of the implementation of the template system, my personal favorite is template Toolkit, the document is also very rich, the site is http://www.template-toolkit.org/.



Modify the previous index to use an example of a template:


The code is as follows

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:


  code is as follows

<body>
Hello ${world}
</body

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.