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

问题描述:

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

我在找东西沿着这些路线:

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

的“$ asInt中(ID)”是由语法,我使用它只是描述了我想做的事情。

我可以很容易地找到examples如何使用路由和指令的高级API来做到这一点,但我找不到任何与低级API。这可能与低级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 
    } 
} 

使用示例(其中期望路径为 “/事件/ $ {EVENTTYPE}”)

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

更复杂的场景可以通过将呼叫链接到/来处理,以致电/!结束。

我发现在阿卡用户名单后说,低级别的API不支持此类型的路径段提取的:

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

接法可以是使用路由API或我们自己解析路径字符串。