如何在简单的perl Web服务器中运行cgi脚本

时间:2014-05-10 12:08:45

标签: perl webserver cgi

对于即将到来的学校项目,我需要实现一个简单的Web服务器,它来自书籍" Net编程与Perl"。我试图全身心投入,因为这对我来说都是新手。现在,我想要做的就是将一个cgi脚本作为主页运行。 我需要从Web服务器附带的Web.pm脚本中获取代码(本书第15章)。

我可以将它作为主页提供cgi文件,但它只显示代码。我尝试了很多东西,最接近的是脚本应该生成的html显示在运行Web服务器的命令行窗口中,但是服务器从not_found子例程输出消息。

以下是带有handle_connection和lookup_file子例程的Web.pm代码的开头(直接来自本书)我离开的子例程是: invalid_request,redirect和not_found

package Web;

use strict;
use vars '@ISA','@EXPORT';
use IO::File;
use CGI;
require Exporter;

@ISA = 'Exporter';
@EXPORT = qw(handle_connection docroot);
# set to your home directory
my $DOCUMENT_ROOT = '.';
my $CRLF = "\015\012";
###############################
sub docroot {
  $DOCUMENT_ROOT = shift if @_;
  return $DOCUMENT_ROOT;
}
###############################
# Outline of Handle_Connection()
# Set the socket handle supplied as a parameter
# Set the standard end-of-line character for HTTP messages
# Read the contents from the socket handle into a request variable
# SECTION TO CHECK FOR ERRORS
    # Check to make sure the main request line has the right string format. Call invalid_request() otherwise. Set $method to GET or HEAD, and $url to the supplied URL
    # Call lookup_file() to find the specified $url in the file system. Call not_found() if lookup_file() fails 
    # If the type of 'file' return from lookup_file() is actually a directory, call redirect()
# Print the status line and the headers for the response to the socket handle (ie. to the client)
# If the HTTP method is “GET”, print the file requested in the URL to the socket handle (ie. to the client)

sub handle_connection {
  my $c = shift;   # socket
  my ($fh,$type,$length,$url,$method);
  local $/ = "$CRLF$CRLF";              # set end-of-line character
  my $request = <$c>;                   # read the request header
  print  $request;       # print request to the command line

  # error checking
  return invalid_request($c) 
    unless ($method,$url) = $request =~ m!^(GET|HEAD) (/.*) HTTP/1\.[01]!;     
  return not_found($c) unless ($fh,$type,$length) = lookup_file($url);
  return redirect($c,"$url/") if $type eq 'directory';

  # print the header to socket
  print $c "HTTP/1.0 200 OK$CRLF";
  print $c "Content-length: $length$CRLF";
  print $c "Content-type: $type$CRLF";

    print $c $CRLF;

  return unless $method eq 'GET';
   # print the content to socket
  my $buffer;
  while ( read($fh,$buffer,1024) ) {
    print $c $buffer;
  }
  close $fh;
}

cgi文件如下

#!/usr/bin/perl -w

# from http://perl.about.com/od/cgiweb/a/perlcgipm.htm

use CGI qw/:standard/;
print header,               
start_html('Hello World'),      
h1('CGI.pm is simple.'),
end_html;

cgi在Apache上工作正常。

我相信我需要进行系统调用,但我的所有努力都没有成功。

非常感谢任何帮助。

0 个答案:

没有答案