我想出了一种在Perl中创建快速Web服务器的方法:
#!/usr/bin/env perl -s -wl
use strict;
use HTTP::Daemon;
use HTTP::Headers;
use HTTP::Response;
sub help {
print "$0 -port=<port-number>";
}
our $port;
our $addr = "localhost";
$port = 9000 unless defined $port;
my $server = HTTP::Daemon->new(
LocalAddr => $addr,
LocalPort => $port,
Listen => 1,
Reuse => 1,
);
die "$0: Could not setup server" unless $server;
print "$0: http://$addr:$port Accepting clients";
while (my $client = $server->accept()) {
print "$0: Client received";
$client->autoflush(1);
my $request = $client->get_request;
print "$0: Client's Request Received";
print "$0: Request: " . $request->method;
if ($request->method eq 'GET') {
my $header = HTTP::Headers->new;
$header->date( time );
$header->server("$0");
$header->content_type('text/html');
my $content = "<!doctype html><html><head><title>Hello World</title></head><body><h1>Hello World!</h1></body></html>";
my $response = HTTP::Response->new(200);
$response->content($content);
$response->header("Content-Type" => "text/html");
$client->send_response($response);
}
print "$0: Closed";
$client->close;
undef($client);
}
但出于某种原因,每次访问localhost:9000
时,它都会显示HTTP标头的一部分 - 日期,服务器,内容长度和内容类型 - 以及内容。它不会将其呈现为HTML页面。有什么我想念的吗?
答案 0 :(得分:4)
这是由-l
开关引起的:
#!/usr/bin/env perl -s -wl
^
它将输出记录分隔符设置为输入记录分隔符(换行符)的值,这会导致向HTTP服务器输出添加其他换行符,并且HTTP响应也会中断。