1

所以我的问题是我安装了 perl5.8,我无法安装任何额外的模块。(我是一名公务员,我必须使用服务器,因为它们没有任何权利或选择我可以在其上安装的内容,修改某些东西的过程需要数年时间)。

所以有一个小的网络服务器脚本:

use HTTP::Daemon;
use HTTP::Status;

(my $d = new HTTP::Daemon 
LocalAddr => '127.0.0.1',
LocalPort => 52443
) || die;
print "Please contact me at: <URL:", $d->url, ">\n";
while (my $c = $d->accept) {
    while (my $r = $c->get_request) {
        if ($r->method eq 'GET' and $r->uri->path eq "/xyzzy") {
            # remember, this is *not* recommended practice :-)
            $c->send_file_response("D:/Script/index.html");
        }
        else {
            $c->send_error(RC_FORBIDDEN)
        }
    }
    $c->close;
    undef($c);
}

我想返回一个像这样的json:{“Status”:“Ok”}

问候

4

1 回答 1

1

重写文档中的示例以返回 JSON 将如下所示:

#!/usr/bin/perl

use strict;
use warnings;

use HTTP::Daemon;
use HTTP::Status;
use HTTP::Response;
use HTTP::Headers;
use JSON::PP;

my $headers = HTTP::Headers->new;
$headers->header(Content_Type => 'application/json');
my $content = JSON::PP->new->utf8->encode({ Status => 'Ok' });

my $d = HTTP::Daemon->new || die;
print "Please contact me at: <URL:", $d->url, ">\n";
while (my $c = $d->accept) {
    while (my $r = $c->get_request) {
        if ($r->method eq 'GET' and $r->uri->path eq "/xyzzy") {
            $c->send_response(
                HTTP::Response->new(200, 'OK', $headers, $content)
            );
        }
        else {
            $c->send_error(RC_FORBIDDEN)
        }
    }
    $c->close;
    undef($c);
}

但请注意,在这个级别编写 Web 应用程序很少有用。你真的很想安装一个 web 框架(我喜欢Dancer2),因为这会让你的生活更轻松。

我不确定是什么对您施加了这些限制。但是,如果您没有使用现代版本的 Perl(至少 5.10)并从 CPAN 安装模块,那么您的 Perl 开发事业将比需要的困难得多。

于 2019-09-20T10:32:48.097 回答