2016-12-26 84 views
1

我試圖使用akka-http低級API實現REST API。我需要匹配包含資源ID的路徑的請求,例如「/ users/12」,其中12是用戶的ID。如何匹配URL中的路徑段與Akka-http低級API

我在找東西沿着這些路線:

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

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

我可以很容易地找到examples如何使用路由和指令的高級API來做到這一點,但我找不到任何與低級API。這可能與低級API有關嗎?

回答

0

我的團隊已經找到了一個很好的解決方案,以這樣的:

/** 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 _ => 
} 

更復雜的場景可以通過將呼叫鏈接到/來處理,以致電/!結束。