【问题标题】:Web Server with HTTP::Daemon, HTML not rendering带有 HTTP::Daemon 的 Web 服务器,HTML 不呈现
【发布时间】:2011-09-19 21:12:15
【问题描述】:

我找到了一种在 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 页面。我有什么遗漏吗?

【问题讨论】:

    标签: perl


    【解决方案1】:

    这是由-l 开关引起的:

    #!/usr/bin/env perl -s -wl
                             ^
    

    它将输出记录分隔符设置为输入记录分隔符的值(换行符),这会导致向 HTTP 服务器输出添加额外的换行符,并导致 HTTP 响应中断。

    【讨论】:

      猜你喜欢
      • 2021-08-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-22
      • 2017-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-25
      相关资源
      最近更新 更多