gpt4 book ai didi

microservices - 如何在 Cro 中插入一些路由检查中间件?

转载 作者:行者123 更新时间:2023-12-03 15:35:02 24 4
gpt4 key购买 nike

假设我需要在提供一些结果之前检查一些 URI。我可以做这样的事情:

sub type-routes {
route {
get -> Str $type where $type ∈ @food-types {
my %ingredients-table = $rrr.calories-table;
my @result = %ingredients-table.keys.grep: {
%ingredients-table{$_}{$type} };
content 'application/json', @result;
}
get -> Str $type where $type ∉ @food-types {
not-found;
}
}
}

基本上,在这种情况下,现有产品和非现有产品的签名不同。但是,将在所有路由中使用相同的 URI。能够在任何路由匹配之前检查它会很有趣,这样当它到达路由块时,我们就知道它没问题。这样它也可以在不同的路线上重复使用。

我查了 before and before-match ,显然您可以做到,但是您需要分析请求对象才能做到这一点,没有简单的方法可以做到。

或者,是否有任何定义“回退路由”的方法,以便如果未找到 URI,则返回 not-found ?

最佳答案

在给出中间件答案之前,我在这种情况下的第一个手段通常是 ​​subset 类型:

sub type-routes {
route {
my constant @food-types = <burgers pizzas beer>;
my subset Food of Str where { $^type ∈ @food-types }

get -> Food $type {
my %ingredients-table = $rrr.calories-table;
my @result = %ingredients-table.keys.grep: {
%ingredients-table{$_}{$type} };
content 'application/json', @result;
}
}
}

这样, Food 可以在任意多的路由上使用。不需要回退路由(无论是在这个解决方案中还是在原始问题中)来生成 not-found ,因为当没有路由与路径段匹配时,路由器会自动生成它。

但是,如果想要采用中间件方式,那么最简单的方法是获取 path-segmentsrequest 并检查相应部分:
sub type-routes {
route {
my constant @food-types = <burgers pizzas beer>;
before {
not-found unless request.path-segments[0] ∈ @food-types;
}

get -> Str $type {
content 'application/json', <123 456>;
}
}
}

关于microservices - 如何在 Cro 中插入一些路由检查中间件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61757205/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com