如何用Mojolicious::Lite实现动态路由生成?
实现Mojolicious::Lite动态路由代理请求
需求说明
现有如下Perl代码,执行Perl myscript.pl daemon启动后,访问https://127.0.0.1:3000/test时会固定请求test主机:
use strict; use warnings; use Mojo::UserAgent; use Mojolicious::Lite; get '/test' => sub { my $host = 'test'; my ( $c ) = @_; my $ua = Mojo::UserAgent->new; my $tx = $ua->get($host => {accept => 'application/json'}); return $c->render( json => $tx->res->json ); }; app->start;
希望实现动态路由:访问https://127.0.0.1:3000/test2时自动请求test2主机,访问任意https://127.0.0.1:3000/xxx路径时,自动请求xxx主机。
解决方案
使用Mojolicious::Lite的路由占位符即可实现动态匹配,修改后的完整代码如下:
use strict; use warnings; use Mojo::UserAgent; use Mojolicious::Lite; # 用:target_host占位符匹配路径中的动态部分 get '/:target_host' => sub { my ( $c ) = @_; # 从路由参数中获取动态主机名 my $host = $c->param('target_host'); my $ua = Mojo::UserAgent->new; # 用动态获取的主机名发起请求 my $tx = $ua->get($host => {accept => 'application/json'}); # 增加错误处理:外部请求失败时返回错误信息 if ($tx->error) { return $c->render( json => { error => $tx->error->{message} }, status => 500 ); } return $c->render( json => $tx->res->json ); }; app->start;
关键说明
- 路由定义
/:target_host中的:target_host是动态占位符,会匹配URL路径中/后的任意非空片段(如test2、abc等) - 通过
$c->param('target_host')可以直接获取占位符对应的实际值,以此作为要请求的外部主机地址 - 新增错误处理逻辑,避免外部主机请求失败时返回空数据或服务崩溃,提升代码健壮性
内容的提问来源于stack exchange,提问作者dave
相关产品推荐
相关产品推荐

