简体   繁体   English

具有HTTP :: Daemon的Web服务器,HTML无法呈现

[英]Web Server with HTTP::Daemon, HTML not rendering

I figured out a way to create a quick web server in Perl: 我想出了一种在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);
}

But for some reason, every time I access localhost:9000 it displays part of the HTTP Header - date, server, content-length and content-type - and the content. 但是由于某种原因,每次我访问localhost:9000它都会显示HTTP标头的一部分-日期,服务器,内容长度和内容类型-以及内容。 It doesn't render it as an HTML page. 它不会将其呈现为HTML页面。 Is there something I'm missing? 有什么我想念的吗?

This is caused by the -l switch: 这是由-l开关引起的:

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

It sets the output record separator to the value of the input record separator (a newline), which results in additional newlines being added to HTTP server output, and a broken HTTP response. 它将输出记录分隔符设置为输入记录分隔符的值(换行符),这将导致其他换行符添加到HTTP服务器输出中,并且HTTP响应中断。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM