You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Mojolicious的Under路由中渲染根路径端点?

在Mojolicious中使用under时让根路径渲染内容的方法

要在保留under中间件逻辑的同时,让根路径/渲染指定内容,只需要给under返回的路由对象添加一个空路径的GET路由即可——因为under('/')的前缀是根路径,空路径就对应最终的/端点。

针对根路径示例的修改代码

my $auth = $r->under('/' => sub ($c) {
    # Authenticated
    return 1 if $c->req->headers->header('X-Bender');
    # Not authenticated
    $c->render(text => "You're not Bender.", status => 401);
    return undef;
});
# 新增根路径路由,直接渲染指定内容
$auth->get('')->to(sub ($c) { $c->render(text => "Hello, world !") });
$auth->get('/blackjack')->to('hideout#blackjack');

访问http://localhost:3000/时,会先经过under的认证逻辑:请求头带有X-Bender则渲染"Hello, world !",否则返回401未认证提示。

针对/company场景的实现

对于/company、/company/products、/company/services的路由树,同样可以用这个思路,让父路径/company渲染首页,同时子路由共享/company下的under逻辑:

my $company = $r->under('/company' => sub ($c) {
    # 这里编写共享逻辑,比如验证公司权限、加载基础数据等
    # 验证通过返回1,不通过则渲染错误并返回undef
    return 1;
});
# 让/company路径渲染首页
$company->get('')->to('company#index');
# 子路由自动继承under的共享逻辑
$company->get('/products')->to('company#products');
$company->get('/services')->to('company#services');

访问/company时会执行共享逻辑后渲染首页,访问/company/products和/company/services时,也会先执行under中的共享代码,再处理各自的控制器逻辑。

内容的提问来源于stack exchange,提问作者mvanle

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 01:03:15