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

Akka-HTTP路由问题:如何匹配/users、/users/abc及/users/abc/xyz路径

Akka-HTTP 路由匹配多层级路径的解决方案

现有路由仅能匹配/users和单层级的/users/abc,无法匹配多层级的/users/abc/xyz,问题出在代码仅拼接了单个segment(),只能捕获一层路径段。

要同时匹配这三类路径,可利用Akka-HTTP的remaining()匹配users之后的所有剩余路径段(包括空路径),同时保留对剩余路径的捕获,修改后的代码如下:

@Override
public PathMatcher1<String> getPath() {
    return PathMatchers.segment("users")
            // 匹配可选的斜杠+剩余所有路径段,空对应/users的情况
            .concat(PathMatchers.optional(PathMatchers.slash().concat(PathMatchers.remaining())))
            // 将Optional转为非空String,空时返回""
            .map(optionalRemaining -> optionalRemaining.orElse(""));
}

代码说明

  • segment("users"):匹配开头的users路径段
  • optional(slash().concat(remaining())):处理users之后的可选路径,当仅访问/users时,这部分返回空的Optional;当访问/users/abc或/users/abc/xyz时,返回对应剩余路径的字符串
  • map(...):将Optional<String>转为普通String,满足PathMatcher1<String>的返回类型要求,空场景下返回空字符串

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 20:27:15