如何将 URI 中的路径段与 Akka-http 低级匹配 API

How to match path segments in URI with Akka-http low-level API

我正在尝试使用 akka-http 低级 API 实现 REST API。我需要匹配包含资源 ID 的路径请求,例如“/users/12”,其中 12 是用户的 ID。

我正在寻找类似的东西:

case HttpRequest(GET, Uri.Path("/users/$asInt(id)"), _, _, _) =>
   // id available as a variable

“$asInt(id)”是一个编造的语法,我用它来描述我想做的事情。

我可以很容易地找到 examples 如何使用路由和指令在高级别 API 中执行此操作,但我找不到低级别 API 的任何内容.低级 API?

可能吗?

我在Akka用户列表中发现一个post说低级API不支持这种路径段提取:

https://groups.google.com/forum/#!topic/akka-user/ucXP7rjUbyE/discussion

备选方案是使用路由 API 或自己解析路径字符串。

我的团队找到了一个很好的解决方案:

/** matches to "/{head}/{tail}" uri path, where tail is another path */
object / {
  def unapply(path: Path): Option[(String, Path)] = path match {
    case Slash(Segment(element, tail)) => Some(element -> tail)
    case _ => None
  }
}

/** matches to last element of the path ("/{last}") */
object /! {
  def unapply(path: Path): Option[String] = path match {
    case Slash(Segment(element, Empty)) => Some(element)
    case _ => None
  }
}

用法示例(期望路径为“/event/${eventType}”)

val requestHandler: HttpRequest => Future[String] = {
  case HttpRequest(POST, uri, _, entity, _)  =>
      uri.path match {
        case /("event", /!(eventType)) =>
        case _ =>
     }
  case _ =>
}

更复杂的场景可以通过链式调用 / 来处理,最后调用 /!