捕获 Akka/Java 中的所有路径段

Capture all segments of path in Akka/Java

我正在尝试使用 Java.

捕获 AkkaHTTP 中 URL 路径的每一段

这是我的代码:

public Route routes() {
    return route(pathPrefix("users", () ->
        route(
            getOrPostUsers(),
            path(PathMatchers.segment(), name -> route(
                getUser(name),
                deleteUser(name),
                path(PathMatchers.segment(), countryOfResidence -> route(
                  getUser(name, countryOfResidence),
                  deleteUser(name, countryOfResidence)
                ))
              )
            )

        )
    ));
}

因此,如您所见,我试图获取 URL 路径的第一段并将其存储为 name 和 URL 路径的第二段并将其存储为 countryOfResidence。举个例子 URL 这样的

localhost:8080/users/ian/usa

如果用户只输入 localhost:8080/users/ian,我想路由到函数 getUser() 或 deleteUser() 的版本,具体取决于 HTTP 请求的类型,它只接受一个名称。如果用户输入更长的 URL,如上所述,我想调用带有两个参数的 getUser() 或 deleteUser() 版本。

每当我 运行 上面的代码时,名称的 PathMatcher 工作得很好。当我 运行 name 和 countryOfResidence 的 PathMatcher 时,问题就出现了。这些路由中的代码永远不会 运行s,并且服务器不会 return 任何 JSON.

我认为问题在于指令是按顺序尝试的,因此较短的指令将在尝试更具体的指令之前匹配。我建议您尝试:

  • 将最具体的路径放在第一位 (path(PathMatchers.segment(), countryOfResidence ...),以便它可以在较短的路径匹配之前匹配或

  • 用匹配 pathEndOrSingleSlash() 的指令为较短的情况添加后缀,这样它们就不会明确匹配较长的路径:

        path(PathMatchers.segment(), name -> route(
            pathEndOrSingleSlash(() -> route(
              getUser(name),
              deleteUser(name)
            ),
            path(PathMatchers.segment(), countryOfResidence -> route(
              getUser(name, countryOfResidence),
              deleteUser(name, countryOfResidence)
            ))
          )
        )