带有正则表达式的 Http Akka 路由未编译

Http Akka route with regular expression is not compiling

我正在将 Http Akka 与 Scala 结合使用。 我有这条路线:

object Route {
  val route =

    path("items" / "card" / """\w+""".r) {
      get {
        complete {
          EntitiesData.someEntity
        }
      }
    }
}

出于某种原因,它没有编译并出现此错误:

Error:(18, 11) type mismatch;
 found   : akka.http.scaladsl.server.Route
    (which expands to)  akka.http.scaladsl.server.RequestContext => scala.concurrent.Future[akka.http.scaladsl.server.RouteResult]
 required: String => (akka.http.scaladsl.server.RequestContext => scala.concurrent.Future[akka.http.scaladsl.server.RouteResult])
      get {

当我删除正则表达式部分或将其更改为常规字符串时,一切似乎都正常。

您需要将代码修改为:

object Route {
  val route =

    path("items" / "card" / """\w+""".r) { matched =>
      get {
        complete {
          EntitiesData.someEntity
        }
      }
    }
}

来自 Akka PathMatcher DSL 文档:

You can use a Regex instance as a PathMatcher1[String], which matches whatever the regex matches and extracts one String value. A PathMatcher created from a regular expression extracts either the complete match (if the regex doesn't contain a capture group) or the capture group (if the regex contains exactly one capture group). If the regex contains more than one capture group an IllegalArgumentException will be thrown.

因此,当您在路径指令中使用正则表达式时,它会将匹配的部分传递到该指令下的部分。那就是您的代码中缺少的内容。