Mojolicious-和-curl-配合调试-HTTP-请求

用 Mojolicious 开启一个 Web 服务器, 接收来自 curl 的请求, 并输出到终端.

安装和下载 Mojolicious

1
cpanm Mojolicious

编写 Web 脚本

1
2
3
mkdir test
touch myapp.pl
chmod +x myapp.pl

myapp.pl 文件内容为:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#!/usr/bin/perl
use strict;
use warnings;
use Mojolicious::Lite;
use Mojo::Util qw(xml_escape);

# 路由处理
any '/test' => sub {
my $c = shift;

# 获取请求方法和路径
my $method = $c->req->method;
my $path = $c->req->url->path;

# 获取所有头字段
my $headers = $c->req->headers->to_hash;

# 获取请求主体(如果有)
my $body = $c->req->body;

# 在终端打印请求的起始行
print "Request Line: $method $path HTTP/1.1\n";

# 在终端打印所有头字段
print "Headers:\n";
foreach my $header (keys %$headers) {
print " $header: $headers->{$header}\n";
}

# 在终端打印请求主体
if ($body) {
print "Body:\n$body\n";
}

# 构建响应
my $response = "<html><body>";
$response .= "<h1>Request Details</h1>";
$response .= "<p><strong>Request Line:</strong> $method $path HTTP/1.1</p>";
$response .= "<h2>Headers:</h2><ul>";

foreach my $header (keys %$headers) {
$response .= "<li><strong>" . ucfirst($header) . ":</strong> " . $headers->{$header} . "</li>";
}

$response .= "</ul>";

if ($body) {
$response .= "<h2>Body:</h2><pre>" . xml_escape($body) . "</pre>";
}

$response .= "</body></html>";

$c->render(text => $response, format => 'html');
};

# 启动应用程序
app->start;

启动 http 服务:

1
./myapp.pl daemon -l "http://*:8111"

使用 curl 测试

发送 GET 请求

1
curl -v http://localhost:8111/test

发送 POST 请求

1
2
3
4
curl -v -X POST http://localhost:8111/test \
-H "Content-Type: application/x-www-form-urlencoded" \
-H "Custom-Header: value" \
--data "param1=value1&param2=value2"

Mojolicious-和-curl-配合调试-HTTP-请求
http://example.com/2024/07/05/Mojolicious-和-curl-配合调试-HTTP-请求/
作者
Jie
发布于
2024年7月5日
许可协议