使用 HTTP::Server::Simple 实现轻量级 HTTP 服务器

在Perl中,HTTP::Server::Simple 模块提供了一种轻量级的方式来实现HTTP服务器。该模块简单易用,适合快速开发和测试HTTP服务。本文将详细介绍如何使用 HTTP::Server::Simple 模块创建和配置一个轻量级HTTP服务器。

安装 HTTP::Server::Simple

首先,需要确保安装了 HTTP::Server::Simple 模块。如果尚未安装,可以使用以下命令通过CPAN进行安装:

复制代码
cpan HTTP::Server::Simple
​

或者,如果你使用的是 cpanm,可以通过以下命令安装:

复制代码
cpanm HTTP::Server::Simple
​

创建简单的 HTTP 服务器

以下示例展示了如何创建一个最简单的HTTP服务器,该服务器在本地端口8080上运行,并返回一个简单的"Hello, World!"消息。

复制代码
use strict;
use warnings;
use HTTP::Server::Simple::CGI;

# 创建一个简单的服务器类,继承自HTTP::Server::Simple::CGI
{
    package MyWebServer;
    use base qw(HTTP::Server::Simple::CGI);

    sub handle_request {
        my ($self, $cgi) = @_;
        print "HTTP/1.0 200 OK\r\n";
        print $cgi->header,
              $cgi->start_html('Hello'),
              $cgi->h1('Hello, World!'),
              $cgi->end_html;
    }
}

# 实例化并启动服务器
my $server = MyWebServer->new(8080);
print "Server is running on http://localhost:8080\n";
$server->run();
​

以上代码创建了一个继承自 HTTP::Server::Simple::CGI 的简单服务器类 MyWebServer ,并重写了 handle_request 方法来处理请求。

扩展服务器功能

可以通过扩展 handle_request 方法来增加服务器的功能。例如,解析请求路径并返回不同的内容:

复制代码
use strict;
use warnings;
use HTTP::Server::Simple::CGI;

{
    package MyWebServer;
    use base qw(HTTP::Server::Simple::CGI);

    sub handle_request {
        my ($self, $cgi) = @_;
        my $path = $cgi->path_info;

        if ($path eq '/hello') {
            print "HTTP/1.0 200 OK\r\n";
            print $cgi->header,
                  $cgi->start_html('Hello'),
                  $cgi->h1('Hello, World!'),
                  $cgi->end_html;
        } elsif ($path eq '/goodbye') {
            print "HTTP/1.0 200 OK\r\n";
            print $cgi->header,
                  $cgi->start_html('Goodbye'),
                  $cgi->h1('Goodbye, World!'),
                  $cgi->end_html;
        } else {
            print "HTTP/1.0 404 Not Found\r\n";
            print $cgi->header,
                  $cgi->start_html('Not Found'),
                  $cgi->h1('404 - Not Found'),
                  $cgi->end_html;
        }
    }
}

my $server = MyWebServer->new(8080);
print "Server is running on http://localhost:8080\n";
$server->run();
​

在这个示例中,服务器根据请求路径返回不同的内容。对于 /hello路径,返回"Hello, World!"消息;对于 /goodbye路径,返回"Goodbye, World!"消息;对于其他路径,返回404错误。

添加日志记录

为了便于调试和监控,可以添加日志记录功能,记录每个请求的信息:

复制代码
use strict;
use warnings;
use HTTP::Server::Simple::CGI;
use POSIX qw(strftime);

{
    package MyWebServer;
    use base qw(HTTP::Server::Simple::CGI);

    sub handle_request {
        my ($self, $cgi) = @_;
        my $path = $cgi->path_info;

        # 记录请求信息
        my $log_entry = strftime("[%Y-%m-%d %H:%M:%S]", localtime) . " - $path\n";
        open my $log, '>>', 'server.log' or die "Cannot open log file: $!";
        print $log $log_entry;
        close $log;

        if ($path eq '/hello') {
            print "HTTP/1.0 200 OK\r\n";
            print $cgi->header,
                  $cgi->start_html('Hello'),
                  $cgi->h1('Hello, World!'),
                  $cgi->end_html;
        } elsif ($path eq '/goodbye') {
            print "HTTP/1.0 200 OK\r\n";
            print $cgi->header,
                  $cgi->start_html('Goodbye'),
                  $cgi->h1('Goodbye, World!'),
                  $cgi->end_html;
        } else {
            print "HTTP/1.0 404 Not Found\r\n";
            print $cgi->header,
                  $cgi->start_html('Not Found'),
                  $cgi->h1('404 - Not Found'),
                  $cgi->end_html;
        }
    }
}

my $server = MyWebServer->new(8080);
print "Server is running on http://localhost:8080\n";
$server->run();
​

此代码段通过将每个请求的信息记录到 server.log 文件中,帮助开发者了解服务器的运行情况和请求历史。

相关推荐
可涵不会debug13 小时前
dufs轻量文件服务器教程:中文界面、WebDAV、上传分享与远程访问
运维·服务器
木子欢儿15 小时前
Ubuntu 26.04 LTS 安装Python 3.12
linux·运维·服务器·python·ubuntu
流浪00116 小时前
计算机网络篇25:应用层——HTTPS 协议原理:非对称加密协商密钥,CA 证书挡住中间人
网络协议·计算机网络·https·非对称加密·对称加密·ca证书
FlightYe16 小时前
音视频修炼之容器与协议(六):HTTP 协议
android·linux·网络·网络协议·算法·http·音视频
小飞在努力16 小时前
【实现负载均匀在线判题④】接入 cpp-httplib 实现编译服务 HTTP 网络化
c语言·开发语言·c++·笔记·http
wdfk_prog18 小时前
LWIP教程 33:从 `https_ex_init()` 到 `http_recv()`——altcp、mbedTLS、TLS Handshake 与 HTTPS 数据通路
网络协议·http·https
Ryan-Zhong19 小时前
AI视频切片 API 怎么用?长视频拆条、高光识别与自动分发接口实测
服务器·数据库·音视频
渴了喝洗衣液19 小时前
第一阶段项目
linux·运维·服务器
蹊黎1 天前
Linux 进程概念(四):命令行参数与环境变量
linux·运维·服务器
buhuizhiyuci1 天前
websocket的介绍
网络·websocket·网络协议