Playframework 可以代理现有路由的默认路由

Playframework 可以代理现有路由的默认路由,playframework,routing,Playframework,Routing,假设我有这样的路线: GET /blog/:blogName controllers.blog.show(blogName: String) GET /blog/:blogName/:postId controllers.blog.getPost(blogName: String, postId: Int) 因此,这对于以下URL很好: www.example.com/blog/corporate www.example.com/blog/corporate/123

假设我有这样的路线:

GET   /blog/:blogName          controllers.blog.show(blogName: String)
GET   /blog/:blogName/:postId  controllers.blog.getPost(blogName: String, postId: Int)
因此,这对于以下URL很好:

www.example.com/blog/corporate
www.example.com/blog/corporate/1231
目标是使用标准路由,但我想以某种方式支持以下内容。 假设我希望名为“corporate”的博客的自定义url在此url上工作:

   corporate.example.com
   corporate.example.com/12321
由于操作只是函数,我希望我能以某种方式创建一个“全面”路由,然后将请求简单地代理到现有路由,如

例如,URL:
corporate.Example.com/12321
我想做:

def catchAll(): Action = {

   val blogName = request...  // extract the subdomain "corporate"
   val postId = // ... extract postId from the URL

   controller.blog.getPost(blogName, postId)
}

注意:我可能有100个这样的博客,所以我不能硬编码到路由中。我想知道的是,在我自己手动从URL中筛选出部分后,是否可以通过“代理”将与路由不匹配的请求“代理”到正确的路由,以某种方式重新使用现有路由。

您可以这样定义路由:

# These two routes can do the "proxying"
GET    /                controllers.blog.view
GET    /:postId         controllers.blog.catchAll(postId: Int)

# These can be your fallback routes
GET   /blog/:blogName           controllers.blog.show(blogName: String)
GET   /blog/:blogName/:postId   controllers.blog.getPost(blogName: String, postId: Int)
然后在博客控制器中,您的“代理”功能:

def view = Action.async { request =>
     // request.host = "subdomain.example.com" in your example, though it may be wiser to try a more sophisticated function with  a regex to handle the extraction.
    val subdomain: String = request.host.split('.').head
    show(subdomain)(request)
}

def catchAll(postId: Int) = Action.async { request =>
    val subdomain: String = request.host.split('.').head
    getPost(subdomain, postId)(request)
}
由于控制器函数
show
getPost
返回一个
操作
,应用时是一个函数
Request=>Future[Result]
,我们只需将原始请求传递给
Action.apply

请注意,由于
Action.apply
返回一个
Future
,因此我需要更改
view
catchAll
以使用
Action.async
来处理
Future[Result]